Program to find the shortest path between two vertices in an undirected graph is discussed here. Given a graph, find the shortest path between the given source and destination nodes.
For example, consider the graph given below. We have to find the shortest path between vertices 1 and 5.
1 -> 0 -> 4 -> 5
1 -> 0 -> 2 -> 5
1 -> 2 -> 5
Shortest path: 1 -> 2 -> 5
Number of edges: 2
publicclassSolution {publicstaticArrayList<Integer> getPathBFSHelper(int[][] edges,int sv,int ev,boolean[] visited) {int n =edges.length;HashMap<Integer,Integer> map =newHashMap<>();Queue<Integer> queue =newLinkedList<>();if (sv == ev) {ArrayList<Integer> ans =newArrayList<>();ans.add(sv);return ans; }queue.add(sv); visited[sv] =true;while (!queue.isEmpty()) {int front =queue.remove();for (int i =0; i < n; i++) {if (edges[front][i] ==1&&!visited[i]) {map.put(i, front);queue.add(i); visited[i] =true;if (i == ev) {ArrayList<Integer> ans =newArrayList<>();ans.add(ev);int value =map.get(ev);while (value != sv) {ans.add(value); value =map.get(value); }ans.add(value);return ans; } } } }returnnull; }publicstaticArrayList<Integer> getPathBFS(int[][] edges,int sv,int ev) {boolean[] visited =newboolean[edges.length];returngetPathBFSHelper(edges, sv, ev, visited); }}