Video in progress

You get a maze (0 is a path, 1 is a wall). Find the minimum number of steps from the top-left corner to the bottom-right corner.

I treat the grid as a graph and run BFS: each cell's four neighbors are the edges. I keep distances in a dist array. In an unweighted graph, BFS makes the first path to arrive the shortest. O(rows·cols).

📖 Answer

static int shortestPath(int[][] grid) {
    int r = grid.length, c = grid[0].length;
    if (grid[0][0] == 1 || grid[r - 1][c - 1] == 1) return -1;
    int[][] dist = new int[r][c];
    for (int[] row : dist) Arrays.fill(row, -1);
    int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

    Deque<int[]> q = new ArrayDeque<>();
    q.offer(new int[]{0, 0});
    dist[0][0] = 0;
    while (!q.isEmpty()) {
        int[] cell = q.poll();
        if (cell[0] == r - 1 && cell[1] == c - 1) return dist[r - 1][c - 1];
        for (int[] d : dirs) {
            int nr = cell[0] + d[0], nc = cell[1] + d[1];
            if (nr < 0 || nc < 0 || nr >= r || nc >= c) continue;
            if (grid[nr][nc] == 1 || dist[nr][nc] != -1) continue;
            dist[nr][nc] = dist[cell[0]][cell[1]] + 1;
            q.offer(new int[]{nr, nc});
        }
    }
    return -1;   // unreachable
}

dist is also the "visited" mark at the same time, so no separate visited is needed.

Why not DFS? DFS also reaches the end, but the first path it finds isn't necessarily the shortest. If you compare all paths, the time becomes exponential.

If the cells have different "costs" (say a swamp counts as 5 steps), plain BFS doesn't work and you need Dijkstra. If the costs are only 0 and 1, 0-1 BFS (pushing to the front and back of a deque) is enough.