|
| 1 | +/* |
| 2 | +Shortest Path in Binary Matrix |
| 3 | +============================== |
| 4 | +
|
| 5 | +In an N by N square grid, each cell is either empty (0) or blocked (1). |
| 6 | +
|
| 7 | +A clear path from top-left to bottom-right has length k if and only if it is composed of cells C_1, C_2, ..., C_k such that: |
| 8 | +
|
| 9 | +Adjacent cells C_i and C_{i+1} are connected 8-directionally (ie., they are different and share an edge or corner) |
| 10 | +C_1 is at location (0, 0) (ie. has value grid[0][0]) |
| 11 | +C_k is at location (N-1, N-1) (ie. has value grid[N-1][N-1]) |
| 12 | +If C_i is located at (r, c), then grid[r][c] is empty (ie. grid[r][c] == 0). |
| 13 | +Return the length of the shortest such clear path from top-left to bottom-right. If such a path does not exist, return -1. |
| 14 | +
|
| 15 | +Example 1: |
| 16 | +Input: [[0,1],[1,0]] |
| 17 | +Output: 2 |
| 18 | +
|
| 19 | +Example 2: |
| 20 | +Input: [[0,0,0],[1,1,0],[1,1,0]] |
| 21 | +Output: 4 |
| 22 | +
|
| 23 | +Note: |
| 24 | +1 <= grid.length == grid[0].length <= 100 |
| 25 | +grid[r][c] is 0 or 1 |
| 26 | +
|
| 27 | +Hint #1 |
| 28 | +Do a breadth first search to find the shortest path. |
| 29 | +
|
| 30 | +*/ |
| 31 | + |
| 32 | +class Solution |
| 33 | +{ |
| 34 | +public: |
| 35 | + int shortestPathBinaryMatrix(vector<vector<int>> &grid) |
| 36 | + { |
| 37 | + if (grid[0][0] == 1) |
| 38 | + return -1; |
| 39 | + |
| 40 | + int n = grid.size(); |
| 41 | + queue<vector<int>> pending; |
| 42 | + pending.push({0, 0}); |
| 43 | + grid[0][0] = 1; |
| 44 | + |
| 45 | + int ans = INT_MAX; |
| 46 | + int steps = 0; |
| 47 | + |
| 48 | + int dir[] = {-1, 0, 1}; |
| 49 | + |
| 50 | + while (pending.size()) |
| 51 | + { |
| 52 | + auto size = pending.size(); |
| 53 | + |
| 54 | + for (int i = 0; i < size; ++i) |
| 55 | + { |
| 56 | + auto curr = pending.front(); |
| 57 | + pending.pop(); |
| 58 | + int x = curr[0], y = curr[1]; |
| 59 | + |
| 60 | + if (x == n - 1 && y == n - 1) |
| 61 | + { |
| 62 | + steps++; |
| 63 | + ans = min(ans, steps); |
| 64 | + continue; |
| 65 | + } |
| 66 | + |
| 67 | + for (int j = 0; j < 3; ++j) |
| 68 | + { |
| 69 | + for (int l = 0; l < 3; ++l) |
| 70 | + { |
| 71 | + |
| 72 | + int nextX = x + dir[j]; |
| 73 | + int nextY = y + dir[l]; |
| 74 | + |
| 75 | + if (nextX < 0 || nextY < 0 || nextX >= n || nextY >= n || (nextX == x && nextY == y) || grid[nextX][nextY]) |
| 76 | + { |
| 77 | + continue; |
| 78 | + } |
| 79 | + else |
| 80 | + { |
| 81 | + grid[nextX][nextY] = 1; |
| 82 | + pending.push({nextX, nextY}); |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + steps++; |
| 88 | + } |
| 89 | + |
| 90 | + return ans != INT_MAX ? ans : -1; |
| 91 | + } |
| 92 | +}; |
0 commit comments