> For the complete documentation index, see [llms.txt](https://shangan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://shangan.gitbook.io/algorithm/he-xin-suan-fa-200-ti/bfs/graph/shortest-path-in-undirected-graph.md).

# Shortest Path in Undirected Graph

{% tabs %}
{% tab title="Java" %}

```java
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;
		}
}
```

{% endtab %}
{% endtabs %}
