【Leetcode】286. Walls and Gates

题目地址:

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)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值