LC 1091. Shortest Path in Binary Matrix

Sarthak Sehgal · May 6, 2020

The idea is to perform a BFS from the position {0,0} to position {n-1,n-1}. We could also perform a DFS but note that BFS always gives us the shortest path so BFS is preferred. The code below is easy to understand and is the standard approach for BFS.

int shortestPathBinaryMatrix(vector<vector<int>>& graph) {
    if (graph[0][0])
        return -1;

    queue<pair<int, int>> q;
    int n = graph.size();
    q.push({0,0});
    int level = 0;

    while (!q.empty()) {
        level++;
        int sz = q.size();

        while (sz--) {
            auto c = q.front();
            q.pop();

            if (c.first == n - 1 && c.second == n - 1) return level;

            // check all 8 directions
            for (auto i = c.first - 1; i <= c.first + 1; ++i)
                for (auto j = c.second - 1; j <= c.second + 1; ++j)
                    if (i == c.first && j == c.second) continue;

                    if (i >= 0 && j >= 0 && i < n && j < n && !graph[i][j]) {
                        q.push({ i, j });
                        graph[i][j] = 1; // this is our way of marking the node as visited as we always check that it is 0 before adding it to the queue
                    }
        }
    }

    return -1;
}

Twitter, Facebook