DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Pattern: DFS Algo

Used in graph traversal where you visit all the nodes at the same level then go on visiting nodes in the next level
E.g. Shortest path in binary matrix

class Solution {
    public int shortestPathBinaryMatrix(int[][] grid) {
        if(grid[0][0]!=0) return -1;
        Queue<Node> q  = new LinkedList<>();
        int dirs[][] = {{0,-1},{0,1},{-1,0},{1,0},{1,1},{-1,-1},{-1,1},{1,-1}};
        q.add(new Node(0,0,1)); // stating point (0,0) with distance 1
        int visited[][] = new int[grid.length][grid[0].length];
        for(int vis[]: visited){
            Arrays.fill(vis, -1);
        }

        while(!q.isEmpty()){
            Node n = q.remove();
            int I = n.i;
            int J = n.j;
            int D = n.d;
            if(I == grid.length-1 && J == grid[0].length-1) return D;
            for(int dir[]: dirs){
                int i = dir[0] + I;
                int j = dir[1] + J;
                if(i<grid.length && j<grid[0].length && i>=0 && j>=0 && grid[i][j] ==0 && visited[i][j]==-1){
                    visited[i][j] = 1;
                    q.add(new Node(i,j, D+1));
                }
            }
        }
        return -1;
    }
}
class Node{
    int i;
    int j;
    int d;
    public Node(int i, int j, int d){
        this.i  =i;
        this.j = j;
        this.d = d;
    }
}
Enter fullscreen mode Exit fullscreen mode

Solved using Dijkstra's single source shortest path- it is Not recommended as it is not that efficient in this case as each step has weight i.e 1

Top comments (0)