Search code examples
javaalgorithmbreadth-first-searchmaze

Printing the shortest path with BFS


I am creating a maze solver which uses Breadth First Search algorithm and I'm wondering if I can somehow print the path on the grid instead of just printing the distance value it travelled in order to find the exit. Here is the code down below and thanks in advance.

    
    public List<Coords> solve(int x, int y) {
        Queue<Coords> q = new LinkedList<>();
        List<Coords> visited = new ArrayList<>();
        Coords start = new Coords(x,y);
        
        q.add(start);
        visited.add(start);
        
        while(!q.isEmpty()) {
            Coords get = q.poll();
            
            if(maze[get.x][get.y] == 3) {
                System.out.println("found an exit!");
                System.out.println("Distance: " + get.dist);
                break;
            }
            
            if(!visited.contains(get)) {
                visited.add(get);
            }
            
            if(isValid(get.x-1, get.y)) {
                q.add(new Coords(get.x-1, get.y, get.dist+1));
            }
            if(isValid(get.x, get.y-1)) {
                q.add(new Coords(get.x, get.y-1, get.dist+1));
            }
            if(isValid(get.x+1, get.y)) {
                q.add(new Coords(get.x+1, get.y, get.dist+1));
            }
            if(isValid(get.x, get.y+1)) {
                q.add(new Coords(get.x, get.y+1, get.dist+1));
            }
            
            
        }
        return visited;
    }
    
}

The output is : found an exit! Distance: 20


Solution

  • I'm not sure I understand the question perfectly, but don't you already have this data in your Queue<Coords> q object?

    If that's the case, then you could have something like this:

    
    if (maze[get.x][get.y] == 3) {
        System.out.println("found an exit!");
        System.out.println("Distance: " + get.dist);
        for(Coords c : q) { 
            System.out.println(c); 
        }
        break;
    }