Give anundirected graph, in which each edge's length is1, and givetwonodes from the graph. We need to find thelengthofthe shortest pathbetween the giventwonodes.
Example
Given graph ={1,2,4#2,1,4#3,5#4,1,2#5,3}, and nodeA =3, nodeB =5.
1------2 3
\ | |
\ | |
\ | |
\ | |
4 5
return1
Code
publicclassSolution { /** * @param graph: a list of Undirected graph node * @param A: nodeA * @param B: nodeB * @return: the length of the shortest path */publicintshortestPath(List<UndirectedGraphNode> graph,UndirectedGraphNode A,UndirectedGraphNode B) {// Write your code hereQueue<UndirectedGraphNode> queue =newLinkedList<>();Set<UndirectedGraphNode> set =newHashSet<>();queue.offer(A);set.add(A);int result =0;while (!queue.isEmpty()) {int size =queue.size(); result++;for (int i =0; i < size; i++) {UndirectedGraphNode current =queue.poll();for (UndirectedGraphNode n :current.neighbors) {if (set.contains(n)) {continue; }if (n.label==B.label) {return result; }queue.offer(n);set.add(n); } } }return-1; }}
Q.双向BFS是否真的能提高效率?
假设单向BFS需要搜索 N 层才能到达终点,每层的判断量为 X,那么总的运算量为X ^ N. 如果换成是双向BFS,前后各自需要搜索 N / 2 层,总运算量为2 * X ^ {N / 2}。如果 N 比较大且X 不为 1,则运算量相较于单向BFS可以大大减少,差不多可以减少到原来规模的根号的量级。