Description
Give an undirected graph, in which each edge’s length is 1, and give two nodes from the graph. We need to find the length of the shortest path between the given two nodes.
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
return 1.
解题思路:
BFS
代码
* Definition for graph node.
* class GraphNode {
* int label;
* ArrayList<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) {
* label = x; neighbors = new ArrayList<UndirectedGraphNode>();
* }
* };
*/
public class Solution {
/**
* @param graph: a list of Undirected graph node
* @param A: nodeA
* @param B: nodeB
* @return: the length of the shortest path
*/
public int shortestPath(List<UndirectedGraphNode> graph, UndirectedGraphNode A, UndirectedGraphNode B) {
// Write your code here
Queue<UndirectedGraphNode> queue = new LinkedList<>();
Set<UndirectedGraphNode> visited = new HashSet<>();
int res = 0;
UndirectedGraphNode last = null;
UndirectedGraphNode upperLast = null;
queue.offer(A);
visited.add(A);
upperLast = A;
while(!queue.isEmpty()){
UndirectedGraphNode now = queue.poll();
if(now.label == B.label){
return res;
}
for(UndirectedGraphNode next: now.neighbors){
if(!visited.contains(next)){
queue.offer(next);
visited.add(next);
last = next;
}
}
if(now == upperLast){
upperLast = last;
res++;
}
}
return -1;//not connected
}
}