Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Graphs

Shortest Path in a Binary Matrix

Medium · Graphs · Asked at Amazon, Google, Meta, Microsoft

In an n × n grid of 0s (open) and 1s (blocked), find the shortest path from the top-left cell to the bottom-right cell moving in any of the 8 directions (including diagonals) through open cells only. Print the number of cells on the path, or -1 if no path exists.

Input

First line: n. Next n lines: n values (0 or 1).

Output

The length of the shortest path in cells, or -1.

Constraints

Every move costs the same, so BFS from the start finds shortest paths. If the start or the end is blocked, the answer is −1 immediately.

Example 1

Input

2
0 1
1 0

Output

2

Example 2

Input

3
0 0 0
1 1 0
1 1 0

Output

4

Example 3

Input

3
1 0 0
1 1 0
1 1 0

Output

-1

Hints

  1. All moves cost one cell, so this is an unweighted shortest path — BFS.
  2. From each cell there are 8 neighbours.
  3. If the start or the target cell is blocked, the answer is −1.

Approach

BFS from (0, 0) with distance 1 (the path length counts cells). Pop cells in order and push every open, unvisited neighbour among the 8 directions with distance + 1. BFS reaches each cell first by a shortest path, so the distance stored at (n − 1, n − 1) is the answer, or −1 if it is never reached.

Complexity: O(n²) time · O(n²) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<vector<int>> g(n, vector<int>(n));
    for (auto &row : g)
        for (auto &x : row) cin >> x;
    if (g[0][0] || g[n - 1][n - 1]) {
        cout << -1 << "\n";
        return 0;
    }
    vector<vector<int>> d(n, vector<int>(n, -1));
    queue<pair<int, int>> q;
    q.push({0, 0});
    d[0][0] = 1;
    while (!q.empty()) {
        auto _b = q.front();
        auto x = _b.first;
        auto y = _b.second;
        q.pop();
        for (int dx = -1; dx <= 1; dx++)
            for (int dy = -1; dy <= 1; dy++) {
                int a = x + dx, b = y + dy;
                if (a >= 0 && b >= 0 && a < n && b < n && !g[a][b] && d[a][b] < 0) {
                    d[a][b] = d[x][y] + 1;
                    q.push({a, b});
                }
            }
    }
    cout << d[n - 1][n - 1] << "\n";
    return 0;
}

Python solution

import sys
from collections import deque

data = sys.stdin.buffer.read().split()
n = int(data[0])
g = [list(map(int, data[1 + i * n : 1 + (i + 1) * n])) for i in range(n)]
if g[0][0] or g[n - 1][n - 1]:
    print(-1)
else:
    d = [[-1] * n for _ in range(n)]
    d[0][0] = 1
    q = deque([(0, 0)])
    while q:
        x, y = q.popleft()
        for dx in (-1, 0, 1):
            for dy in (-1, 0, 1):
                a, b = x + dx, y + dy
                if 0 <= a < n and 0 <= b < n and not g[a][b] and d[a][b] < 0:
                    d[a][b] = d[x][y] + 1
                    q.append((a, b))
    print(d[n - 1][n - 1])

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        int[][] g = new int[n][n];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++) {
                in.nextToken();
                g[i][j] = (int) in.nval;
            }
        if (g[0][0] == 1 || g[n - 1][n - 1] == 1) {
            System.out.println(-1);
            return;
        }
        int[][] d = new int[n][n];
        for (int[] row : d) Arrays.fill(row, -1);
        ArrayDeque<int[]> q = new ArrayDeque<>();
        q.add(new int[] {0, 0});
        d[0][0] = 1;
        while (!q.isEmpty()) {
            int[] c = q.poll();
            for (int dx = -1; dx <= 1; dx++)
                for (int dy = -1; dy <= 1; dy++) {
                    int a = c[0] + dx, b = c[1] + dy;
                    if (a >= 0 && b >= 0 && a < n && b < n && g[a][b] == 0 && d[a][b] < 0) {
                        d[a][b] = d[c[0]][c[1]] + 1;
                        q.add(new int[] {a, b});
                    }
                }
        }
        System.out.println(d[n - 1][n - 1]);
    }
}

Solve Shortest Path in a Binary Matrix online · All practice problems