题目地址:
https://leetcode.com/problems/walls-and-gates/
给定一个二维矩阵,里面含 0 , − 1 , I N F 0,-1,INF 0,−1,INF。 0 0 0表示门, − 1 -1 −1表示障碍物,其余都标记为 I N F INF INF。要求更新矩阵,使得每个 I N F INF INF更新为其在的位置与离其最近的门的距离(路径上不能走到障碍物)。如果走不到门则不必更新。
思路是BFS。先把所有的门的位置入队,然后逐层向外更新,发现能更新为更小值的,就将其更新并将其下标入队。代码如下:
class Solution {
public:
using PII = pair<int, int>;
void wallsAndGates(vector<vector<int>>& g) {
const int INF = (1 << 31) - 1;
int m = g.size(), n = g[0].size();
queue<PII> q;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (!g[i][j]) q.push({i, j});
while (q.size()) {
for (int i = q.size(); i; i--) {
auto t = q.front(); q.pop();
int x = t.first, y = t.second;
static int d[] = {-1, 0, 1, 0, -1};
for (int k = 0; k < 4; k++) {
int nx = x + d[k], ny = y + d[k + 1];
if (0 <= nx && nx < m && 0 <= ny && ny < n && g[nx][ny] == INF) {
g[nx][ny] = g[x][y] + 1;
q.push({nx, ny});
}
}
}
}
}
};
时空复杂度 O ( m n ) O(mn) O(mn)。