您好,欢迎访问一九零五行业门户网

Cracking coding interview(4.2)有向图判断任意2点之间是否有一

4.2 given a directed graph, design an algorithm to find out whether there is a route between two nodes. 1.图的存储使用邻接矩阵 2.使用邻接矩阵的过程中,必须给每个节点编号(0,1...) 3.可以写一个map函数给按一定规则所有节点编号(本例未实现) 4.alg
4.2 given a directed graph, design an algorithm to find out whether 
there is a route between two nodes.
1.图的存储使用邻接矩阵
2.使用邻接矩阵的过程中,必须给每个节点编号(0,1...)
3.可以写一个map函数给按一定规则所有节点编号(本例未实现)
4.algorithm:通过bfs或dfs遍历从其中一个节点开始遍历图,看是否对可达另一个节点。
import java.util.queue;import java.util.linkedlist;import java.util.stack;//vertex in the graph must have serial number//from 0 to n, if graph isn't suitable for this//write map() to map.//directed no-weight graphclass graph1{ private static boolean[][] matrix; private static int vertexnum; public static void generator(int[][] g, int vnum){ vertexnum = vnum; matrix = new boolean[vertexnum][vertexnum]; for(int i=0;i = matrix.length || v2 >= matrix.length) return false; boolean[] isvisited = new boolean[vertexnum]; stack s = new stack(); int v = -1; if(v1 != v2){ s.push(v1); isvisited[v1] = true; } else return true; while(!s.empty()){ v = s.peek();//when v's all next node have been invisted, then pop// system.out.println([+v+]);// boolean marked = false; for(int j=0;j = matrix.length || v2 >= matrix.length) return false; boolean[] isvisited = new boolean[vertexnum]; queue queue = new linkedlist(); int v = -1; queue.offer(v1); isvisited[v1] = true; while(!queue.isempty()){ v = queue.poll(); if(v == v2) return true; for(int j = 0;j :+graph1.isroutebfs(2, 3)); system.out.println(r:+graph1.isroutedfs(2, 3)); }}
其它类似信息

推荐信息