Approach
Breadth-first search
For Shortest Path in Binary Matrix, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 37 lines of C++ from the credited upstream file 1091.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 3 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int shortestPathBinaryMatrix(vector<vector<int>>& grid) {4 const int n = grid.size();5 if (grid[0][0] == 0 && n == 1)6 return 1;7 if (grid[0][0] == 1 || grid.back().back() == 1)8 return -1;9 10 constexpr int kDirs[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1},11 {0, 1}, {1, -1}, {1, 0}, {1, 1}};12 queue<pair<int, int>> q{{{0, 0}}};13 vector<vector<bool>> seen(n, vector<bool>(n));14 seen[0][0] = true;15 16 for (int step = 1; !q.empty(); ++step)17 for (int sz = q.size(); sz > 0; --sz) {18 const auto [i, j] = q.front();19 q.pop();20 for (const auto& [dx, dy] : kDirs) {21 const int x = i + dx;22 const int y = j + dy;23 if (x < 0 || x == n || y < 0 || y == n)24 continue;25 if (grid[x][y] != 0 || seen[x][y])26 continue;27 if (x == n - 1 && y == n - 1)28 return step + 1;29 q.emplace(x, y);30 seen[x][y] = true;31 }32 }33 34 return -1;35 }36};37