题目地址:
https://leetcode.com/problems/shortest-path-in-binary-matrix/
给定一个 0 − 1 0-1 0−1方阵,边长为 n n n,从 ( 0 , 0 ) (0,0) (0,0)出发要走到 ( n − 1 , n − 1 ) (n-1,n-1) (n−1,n−1),要求路径上的数都是 0 0 0,每一步可以走周围的八个方向。问最短路径的长度。
思路是BFS。代码如下:
class Solution {
public:
using PII = pair<int, int>;
int shortestPathBinaryMatrix(vector<vector<int>>& g) {
int m = g.size(), n = g[0].size();
int dx[] = {1, 0, -1, 0, 1, 1, -1, -1};
int dy[] = {0, 1, 0, -1, 1, -1, 1, -1};
if (g[0][0]) return -1;
if (m == 1 && n == 1) return 1;
int res = 1;
queue<PII> q;
q.push({0, 0});
g[0][0] = -1;
while (q.size()) {
res++;
for (int i = q.size(); i; i--) {
auto t = q.front();
q.pop();
for (int j = 0; j < 8; j++) {
int nx = t.first + dx[j], ny = t.second + dy[j];
if (0 <= nx && nx < m && 0 <= ny && ny < n && !g[nx][ny]) {
if (nx == m - 1 && ny == n - 1) return res;
g[nx][ny] = -1;
q.push({nx, ny});
}
}
}
}
return -1;
}
};
时空复杂度 O ( n 2 ) O(n^2) O(n2)。