java圖的最短路徑
A. 用java怎麼用迪傑斯特拉算有向圖有權值的最短路徑
Dijkstra(迪傑斯特拉)演算法是典型的最短路徑路由演算法,用於計算一個節點到其他所有節點的最短路徑。主要特點是以起始點為中心向外層層擴展,直到擴展到終點為止。
Dijkstra一般的表述通常有兩種方式,一種用永久和臨時標號方式,一種是用OPEN, CLOSE表方式
用OPEN,CLOSE表的方式,其採用的是貪心法的演算法策略,大概過程如下:
1.聲明兩個集合,open和close,open用於存儲未遍歷的節點,close用來存儲已遍歷的節點
2.初始階段,將初始節點放入close,其他所有節點放入open
3.以初始節點為中心向外一層層遍歷,獲取離指定節點最近的子節點放入close並從新計算路徑,直至close包含所有子節點
代碼實例如下:
Node對象用於封裝節點信息,包括名字和子節點
[java] view plain
public class Node {
private String name;
private Map<Node,Integer> child=new HashMap<Node,Integer>();
public Node(String name){
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<Node, Integer> getChild() {
return child;
}
public void setChild(Map<Node, Integer> child) {
this.child = child;
}
}
MapBuilder用於初始化數據源,返回圖的起始節點
[java] view plain
public class MapBuilder {
public Node build(Set<Node> open, Set<Node> close){
Node nodeA=new Node("A");
Node nodeB=new Node("B");
Node nodeC=new Node("C");
Node nodeD=new Node("D");
Node nodeE=new Node("E");
Node nodeF=new Node("F");
Node nodeG=new Node("G");
Node nodeH=new Node("H");
nodeA.getChild().put(nodeB, 1);
nodeA.getChild().put(nodeC, 1);
nodeA.getChild().put(nodeD, 4);
nodeA.getChild().put(nodeG, 5);
nodeA.getChild().put(nodeF, 2);
nodeB.getChild().put(nodeA, 1);
nodeB.getChild().put(nodeF, 2);
nodeB.getChild().put(nodeH, 4);
nodeC.getChild().put(nodeA, 1);
nodeC.getChild().put(nodeG, 3);
nodeD.getChild().put(nodeA, 4);
nodeD.getChild().put(nodeE, 1);
nodeE.getChild().put(nodeD, 1);
nodeE.getChild().put(nodeF, 1);
nodeF.getChild().put(nodeE, 1);
nodeF.getChild().put(nodeB, 2);
nodeF.getChild().put(nodeA, 2);
nodeG.getChild().put(nodeC, 3);
nodeG.getChild().put(nodeA, 5);
nodeG.getChild().put(nodeH, 1);
nodeH.getChild().put(nodeB, 4);
nodeH.getChild().put(nodeG, 1);
open.add(nodeB);
open.add(nodeC);
open.add(nodeD);
open.add(nodeE);
open.add(nodeF);
open.add(nodeG);
open.add(nodeH);
close.add(nodeA);
return nodeA;
}
}
圖的結構如下圖所示:
Dijkstra對象用於計算起始節點到所有其他節點的最短路徑
[java] view plain
public class Dijkstra {
Set<Node> open=new HashSet<Node>();
Set<Node> close=new HashSet<Node>();
Map<String,Integer> path=new HashMap<String,Integer>();//封裝路徑距離
Map<String,String> pathInfo=new HashMap<String,String>();//封裝路徑信息
public Node init(){
//初始路徑,因沒有A->E這條路徑,所以path(E)設置為Integer.MAX_VALUE
path.put("B", 1);
pathInfo.put("B", "A->B");
path.put("C", 1);
pathInfo.put("C", "A->C");
path.put("D", 4);
pathInfo.put("D", "A->D");
path.put("E", Integer.MAX_VALUE);
pathInfo.put("E", "A");
path.put("F", 2);
pathInfo.put("F", "A->F");
path.put("G", 5);
pathInfo.put("G", "A->G");
path.put("H", Integer.MAX_VALUE);
pathInfo.put("H", "A");
//將初始節點放入close,其他節點放入open
Node start=new MapBuilder().build(open,close);
return start;
}
public void computePath(Node start){
Node nearest=getShortestPath(start);//取距離start節點最近的子節點,放入close
if(nearest==null){
return;
}
close.add(nearest);
open.remove(nearest);
Map<Node,Integer> childs=nearest.getChild();
for(Node child:childs.keySet()){
if(open.contains(child)){//如果子節點在open中
Integer newCompute=path.get(nearest.getName())+childs.get(child);
if(path.get(child.getName())>newCompute){//之前設置的距離大於新計算出來的距離
path.put(child.getName(), newCompute);
pathInfo.put(child.getName(), pathInfo.get(nearest.getName())+"->"+child.getName());
}
}
}
computePath(start);//重復執行自己,確保所有子節點被遍歷
computePath(nearest);//向外一層層遞歸,直至所有頂點被遍歷
}
public void printPathInfo(){
Set<Map.Entry<String, String>> pathInfos=pathInfo.entrySet();
for(Map.Entry<String, String> pathInfo:pathInfos){
System.out.println(pathInfo.getKey()+":"+pathInfo.getValue());
}
}
/**
* 獲取與node最近的子節點
*/
private Node getShortestPath(Node node){
Node res=null;
int minDis=Integer.MAX_VALUE;
Map<Node,Integer> childs=node.getChild();
for(Node child:childs.keySet()){
if(open.contains(child)){
int distance=childs.get(child);
if(distance<minDis){
minDis=distance;
res=child;
}
}
}
return res;
}
}
Main用於測試Dijkstra對象
[java] view plain
public class Main {
public static void main(String[] args) {
Dijkstra test=new Dijkstra();
Node start=test.init();
test.computePath(start);
test.printPathInfo();
}
}
B. java中如何鄰接矩陣遍歷最短路徑長度
packagetest;
importjava.util.ArrayList;
import清廳java.util.List;
/**
*java-用鄰接矩陣求圖的最短路徑、最長途徑。弗洛伊德演算法
*/
publicclassFloydInGraph{
privatestaticintINF=Integer.MAX_VALUE;
privateint[][]dist;
privateint[][]path;
privateList<Integer>result=newArrayList<Integer>();
publicFloydInGraph(intsize){
this.path=newint[size][size];
this.dist=newint[size][size];
}
publicvoidfindPath(inti,intj){
intk=path[i][j];
答如隱if(k==-1)return;
findPath(i,k);
result.add(k);
findPath(k,j);
}
publicvoidfindCheapestPath(intbegin,intend,int[][]matrix){
floyd(matrix);
result.add(begin);
findPath(begin,end);
result.add(end);
}
publicvoidfloyd(int[][]matrix){
intsize=matrix.length;
for(inti=0;i<size;i++){
for(intj=0;j<size;j++){
path[i][j]=-1;
dist[i][j]=matrix[i][j];
}
}
for(intk=0;k<size;k++){
for(inti=0;i<size;i++){
for(intj=0;j<size;j++){
if(dist[i][k]!=INF&&
dist[k][j]!=INF&&
橡伍dist[i][k]+dist[k][j]<dist[i][j]){//dist[i][k]+dist[k][j]>dist[i][j]-->longestPath
dist[i][j]=dist[i][k]+dist[k][j];
path[i][j]=k;
}
}
}
}
}
publicstaticvoidmain(String[]args){
FloydInGraphgraph=newFloydInGraph(5);
int[][]matrix={
{INF,30,INF,10,50},
{INF,INF,60,INF,INF},
{INF,INF,INF,INF,INF},
{INF,INF,INF,INF,30},
{50,INF,40,INF,INF},
};
intbegin=0;
intend=4;
graph.findCheapestPath(begin,end,matrix);
List<Integer>list=graph.result;
System.out.println(begin+"to"+end+",thecheapestpathis:");
System.out.println(list.toString());
System.out.println(graph.dist[begin][end]);
}
}
C. 求java實現矩陣圖上任意兩點的最短路徑源碼
我用的是遞歸調用方法,有個小問題就是在列印步數的時候是返向的,原因是就是程序不斷的調用自己,到最後判斷基值位準退出調用。這才開始從棧里取出方法進行執行的原因。
代碼欣賞:
publicstaticintstep=1;
=newStringBuffer();
publicstaticint[][]maze={{1,1,1,1,1,1,1,1,1,1,1},
{1,0,1,0,1,0,0,0,0,0,1},
{1,0,1,0,0,0,1,0,1,1,1},
{1,0,0,0,1,0,1,0,0,0,1},
{1,0,1,1,0,0,1,0,0,1,1},//0代表可以通過,1代表不可通過
{1,0,1,0,1,1,0,1,0,0,1},
{1,0,0,0,0,0,0,0,1,0,1},
{1,0,1,0,1,0,1,0,1,0,1},
{1,0,0,1,0,0,1,0,1,0,1},
{1,1,1,1,1,1,1,1,1,1,1}};
publicstaticvoidmain(String[]args){
inti,j;//循環記數變數
Sample.way(1,1);//二維數組起始值從下標1,1開始
System.out.println("起點從坐標x=1,y=1開始");
System.out.println("終點坐標是x=8,y=9結束");
System.out.println("這是迷宮圖表");
System.out.println("012345678910");
System.out.println("+---+---+---+---+---+---+---+---+---+---+---+---+---+");
for(i=0;i<10;i++){
System.out.print(""+i+"‖");
for(j=0;j<11;j++)
System.out.print("-"+maze[i][j]+"-‖");
System.out.println("");
System.out.println("+---+---+---+---+---+---+---+---+---+---+---+---+---+");
}
//列印顯示步數
System.out.print(printStep.toString());
}
publicstaticbooleanway(intx,inty){
if(maze[8][9]==2)//代表遞歸終止條件(也就是當走出出口時標記為2)
returntrue;
else{
if(maze[y][x]==0){
maze[y][x]=2;
/*
*下面if判斷條件代表當前坐標為基點,
*根據判斷對當前位置進行遞歸調用:如:
*往上、往右上、往右、往右下、往下、
*往左下、往左、往左上的坐標是否可走,
*判斷是否可走的返回條件是:
*2代表可通過、1代表不能通過、3表示已經走過,但是未能走通。
*/
if(way(x,y-1)){
printStep.append("第"+step+"步的所走的位置是x="+x+"y="+y+" ");
step++;
returntrue;
}elseif(way(x+1,y-1)){
printStep.append("第"+step+"步的所走的位置是x="+x+"y="+y+" ");
step++;
returntrue;
}elseif(way(x+1,y)){
printStep.append("第"+step+"步的所走的位置是x="+x+"y="+y+" ");
step++;
returntrue;
}elseif(way(x+1,y+1)){
printStep.append("第"+step+"步的所走的位置是x="+x+"y="+y+" ");
step++;
returntrue;
}elseif(way(x,y+1)){
printStep.append("第"+step+"步的所走的位置是x="+x+"y="+y+" ");
step++;
returntrue;
}elseif(way(x-1,y+1)){
printStep.append("第"+step+"步的所走的位置是x="+x+"y="+y+" ");
step++;
returntrue;
}elseif(way(x-1,y)){
printStep.append("第"+step+"步的所走的位置是x="+x+"y="+y+" ");
step++;
returntrue;
}elseif(way(x-1,y-1)){
printStep.append("第"+step+"步的所走的位置是x="+x+"y="+y+" ");
step++;
returntrue;
}else{
maze[y][x]=3;
returnfalse;
}
}else
returnfalse;
}
}
復制代碼前需要樓主自己創建個類
Sample.way(1,1);這句代碼是我的類的靜態調用,改下XXXXX.way(1,1);
XXXXX代表你創建的類。
下面是這個程序運行後的截圖