Shortest Path in Undirected Graph
Example
1------2 3
\ | |
\ | |
\ | |
\ | |
4 5Code
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> set = new HashSet<>();
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;
}
}算法描述
Last updated