I've managed to come up with a working BFS algorithm that returns the entire traversal path, however I'm unsure of how to get the shortest path.
This is my code:
public ArrayList<Node> get_neighbours(Node node, Grid grid) {
ArrayList<Node> neighbours = new ArrayList<>();
int R = grid.getRl();
int C = grid.getCl();
int[] dr = new int[]{-1, +1, 0, 0};
int[] dc = new int[]{0, 0, +1, -1};
for (int i=0; i<4; i++) {
int rr = node.getR() + dr[i];
int cc = node.getC() + dc[i];
if (rr < 0 || cc < 0) continue;
if (rr >= R || cc >= C) continue;
if (grid.getNodes()[rr][cc].getVal() == "V") continue;
if (grid.getNodes()[rr][cc].getVal() == "X") continue;
Node neighbour = grid.getNodes()[rr][cc];
neighbours.add(neighbour);
}
return neighbours;
}
public Queue<Node> find_path_bfs(Node start, Node end, Grid grid) {
Queue<Node> queue = new LinkedList<>();
Queue<Node> path = new LinkedList<>();
queue.add(start);
grid.mark_visited(start.getR(), start.getC());
while (!queue.isEmpty()) {
Node node = queue.remove();
path.add(node);
if (node == end) break;
ArrayList<Node> adj_nodes = get_neighbours(node, grid);
for (Node n : adj_nodes) {
if (!(n.getVal() == "V")) {
queue.add(n);
n.setVal("V");
}
}
}
return path;
}
I took a look at this post, that suggests saving the path to the current node as well, but I'm not sure how to implement this in Java as I would have to have a queue that stores both a Node and a List of Nodes together as one item. My Java is a little rusty, so I'm not sure if this is possible or if there is a better way.