
I am doing my first search on the above chart to find the shortest path from Node 0 to Node 6 .
My code
public List<Integer> shortestPathBFS(int startNode, int nodeToBeFound){ boolean shortestPathFound = false; Queue<Integer> queue = new LinkedList<Integer>(); Set<Integer> visitedNodes = new HashSet<Integer>(); List<Integer> shortestPath = new ArrayList<Integer>(); queue.add(startNode); shortestPath.add(startNode); while (!queue.isEmpty()) { int nextNode = queue.peek(); shortestPathFound = (nextNode == nodeToBeFound) ? true : false; if(shortestPathFound)break; visitedNodes.add(nextNode); System.out.println(queue); Integer unvisitedNode = this.getUnvisitedNode(nextNode, visitedNodes); if (unvisitedNode != null) { queue.add(unvisitedNode); visitedNodes.add(unvisitedNode); shortestPath.add(nextNode);
I need to track the nodes through which BFS works. passed to achieve node 6, for example [0,3,2,5,6] . To do this, I created a list called shortestPath and tried to save the previous nodes of the visited nodes to get a list of nodes. abstract
But that does not work. The shortest path: [0,3,2,5,6]
In the list, I get the Shortest path: [0, 0, 0, 0, 1, 3, 3, 2, 5]
It partially corrects, but gives an additional 1 .
If I start again with the first element 0 the shortestPath list and start moving and returning. For example, 1 does not have an edge to 3 , so I go back and move from 0 to 3 to 5 , I get an answer, but I'm not sure if this is the right way.
What is the ideal way to get nodes for the shortest path?