欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode994. 腐烂的橘子

程序员文章站 2022-05-21 12:09:29
...
//994. 腐烂的橘子
class Solution {
public:
  vector<vector<int>>s;
  vector<vector<int>>f;
  const int inf = 0x3f3f3f3f;
  int m, n;
  bool legal(int i, int j) {
    return (0 <= i && i < n && 0 <= j && j < m);
  }
  void bfs(int i, int j) {
    queue<pair<int, int>>p;
    p.push({ i,j });
    int cnt = -1;
    while (p.size()) {
      cnt++;
      queue<pair<int, int>>q;
      while (p.size()) {
        auto t = p.front(); p.pop();
        int x = t.first;
        int y = t.second;
        if (legal(x, y)) {
          if (s[x][y]) {
            s[x][y] = 0;
            f[x][y] = min(f[x][y], cnt);
            q.push({ x - 1,y });
            q.push({ x,y - 1 });
            q.push({ x + 1,y });
            q.push({ x,y + 1 });
          }
        }
      }
      p = q;
    }
  }
  int orangesRotting(vector<vector<int>>& grid) {
    n = grid.size();
    m = grid[0].size();
    vector<vector<int>>ft(n, vector<int>(m, inf));
    f = ft;
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++)
        if (grid[i][j] == 2) {
          s = grid;
          f[i][j] = 0;
          bfs(i, j);
        }
    int ans = 0;
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++)
        if (grid[i][j]) ans = max(ans, f[i][j]);
    if (ans == inf) return -1;
    return ans;
  }
};