I know the name is a little messy, but I donβt know how to better explain it.
What am I trying to do:
Using the graph found in the text file, find and print the shortest path (minimum number of vertices) from vertex A to vertex B.
Note: use the width search, not Dijkstra's.
What I have:
A working algorithm that applies BFS on a chart but does not have a good way to actually print the shortest path.
I find it difficult to distinguish a vertex in the shortest path from one that is simply executed through the algorithm, but not in the shortest path.
For example: find the shortest path between 0 and 4. 0 connects to 1.2 and 3. 1 connects to 4. My path turns out to be [0,1,2,3,4] instead of [0,1,4].
I was not able to find threads asking the same question, or any BFS passes that include this, so I'm not sure if I am doing this much more complicated than that?
Edit: code for those who might be interested (not sure if I avoid circles?)
Edit 2: Changed the way my stack path is stored.
public String findPath(int v, int w) { Queue<Integer> q = new LinkedList<Integer>(); boolean[] visited = new boolean[g.numVertices()]; q.add(v); Stack<Integer> path = new Stack<Integer>(); while(q.peek() != null) { runBFS(q.poll(),w,visited,q,path); } return path.toString(); } private void runBFS(int v, int w, boolean[] visited, Queue<Integer> q, Stack<Integer> path) { if(visited[v]) { } else if(v == w) { path.add(v); q.clear(); } else { path.add(v); visited[v] = true; VertexIterator vi = g.adjacentVertices(v); while(vi.hasNext()) { q.add(vi.next()); } } }
Some explanation of variables and methods:
v = vertex of origin
w = target vertex
g = graph
vi = normal iterator that iterates over neighbors v
Thank you for reading!