java查找图中两点之间所有路径
本文实例为大家分享了java查找图中两点之间所有路径的具体代码,基于邻接表,供大家参考,具体内容如下
图类:
packagegraph1; importjava.util.LinkedList; importgraph.Graph.edgeNode; publicclassGraph{ classEdgeNode{ intadjvex; EdgeNodenextEdge; } classVexNode{ intdata; EdgeNodefirstEdge; booleanisVisted; publicbooleanisVisted(){ returnisVisted; } publicvoidsetVisted(booleanisVisted){ this.isVisted=isVisted; } } VexNode[]vexsarray; int[]visited=newint[100]; boolean[]isVisited=newboolean[100]; publicvoidlinkLast(EdgeNodetarget,EdgeNodenode){ while(target.nextEdge!=null){ target=target.nextEdge; } target.nextEdge=node; } publicintgetPosition(intdata){ for(inti=0;i算法:
packagegraph1; importjava.util.HashMap; importjava.util.Map; importjava.util.Stack; importjavax.swing.plaf.synth.SynthStyle; importgraph1.Graph.EdgeNode; publicclassFindALlPath{ //代表某节点是否在stack中,避免产生回路 publicMapstates=newHashMap(); //存放放入stack中的节点 publicStack stack=newStack(); //打印stack中信息,即路径信息 publicvoidprintPath(){ StringBuildersb=newStringBuilder(); for(Integeri:stack){ sb.append(i+"->"); } sb.delete(sb.length()-2,sb.length()); System.out.println(sb.toString()); } //得到x的邻接点为y的后一个邻接点位置,为-1说明没有找到 publicintgetNextNode(Graphgraph,intx,inty){ intnext_node=-1; EdgeNodeedge=graph.vexsarray[x].firstEdge; if(null!=edge&&y==-1){ intn=edge.adjvex; //元素还不在stack中 if(!states.get(n)) returnn; return-1; } while(null!=edge){ //节点未访问 if(edge.adjvex==y){ if(null!=edge.nextEdge){ next_node=edge.nextEdge.adjvex; if(!states.get(next_node)) returnnext_node; } else return-1; } edge=edge.nextEdge; } return-1; } publicvoidvisit(Graphgraph,intx,inty){ //初始化所有节点在stack中的情况 for(inti=0;i 测试类:
packagegraph1; importjava.util.Iterator; importgraph1.Graph.VexNode; publicclassTset2{ publicstaticvoidmain(String[]args){ int[]vexs={0,1,2,3,4}; int[][]edges={ {0,1}, {0,3}, {1,0}, {1,2}, {2,1}, {2,3}, {2,4}, {3,0}, {3,2}, {3,4}, {4,2}, {4,3}, }; Graphgraph=newGraph(); graph.buildGraph(vexs,edges); graph.printGraph(); FindALlPathfindALlPath=newFindALlPath(); findALlPath.visit(graph,4,0); } }以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。