# LeetCode 1162. 地图分析【最短路径、广度优先搜索】

### 题目描述

输入：[[1,0,1],[0,0,0],[1,0,1]]



输入：[[1,0,0],[0,0,0],[0,0,0]]



1. 1 <= grid.length == grid[0].length <= 100
2. grid[i][j] 不是 0 就是 1

### 代码

class Solution {
public:
static constexpr int next[4][2] = {{1,  0}, {-1, 0}, {0,  1}, {0,  -1}};
int maxDistance(vector<vector<int>> &grid) {
queue<pair<int, int>> q;

int r = grid.size(), c = grid[0].size();
vector<vector<int>> visit(r, vector<int>(c));

for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j)
if (grid[i][j] == 1) q.emplace(i, j);

if (q.empty() || q.size() == r * c) return -1;

int step = 0;
while (!q.empty()) {
++step;
int level = q.size();
for (int i = 0; i < level; ++i) {
auto front = q.front();
q.pop();
for (auto &direct : next) {
int nx = front.first + direct[0], ny = front.second + direct[1];
if (nx >= 0 && nx < r && ny >= 0 && ny < c && grid[nx][ny] == 0 && !visit[nx][ny]){
q.emplace(nx, ny);
visit[nx][ny] = true;
}
}
}
}

return step - 1;
}
};

05-05 3915

10-17 191
03-29 175
06-02 2427
04-15 847
07-26 500
03-06 77