Shortest Path in Undirected Graph

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) {
			int result = 0;
			Queue<UndirectedGraphNode> queue = new LinkedList<>();
			Set<UndirectedGraphNode> hash = new HashSet<>();
			queue.offer(A);
		hash.add(A);
			while (!queue.isEmpty()) {
				result ++;
				int size = queue.size();
				for (int i = 0; i < size; i++) {
					UndirectedGraphNode cur = queue.poll();
					for (UndirectedGraphNode nei : cur.neighbors) {
					if (nei == B) {
		return result;
					}
					if (!hash.contains(nei)) {
						queue.offer(nei);
						hash.add(nei);
					}
				}
				}
			}
			return -1;
		}
}

最后更新于

这有帮助吗?