解法:bfs
class Solution {
public:int maxDistance(vector<vector<int>>& grid) {if (grid.empty()) return 0;int rows = grid.size(),cols = grid[0].size();vector<vector<int>> dist(rows, vector<int>(cols)); //距离矩阵vector<vector<int>> seen(rows, vector<int>(cols)); //访问标记矩阵int dir[4][2] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } }; //方向数组queue<pair<int,int>> q;for (int i = 0; i < rows; i++) //将所有的 1 的位置放入队列for (int j = 0; j < cols; j++)if (grid[i][j] == 1) {seen[i][j] = 1; //标记为访问过q.push({ i, j }); }if(q.size()==rows*cols || q.empty()) //全是岛屿或海洋,返回-1return -1; while (!q.empty()) {pair<int,int> cur=q.front();q.pop();for (int i = 0; i < 4; i++) { //以每个1为中心向四个方向搜索int nx=cur.first+dir[i][0], ny=cur.second+dir[i][1];if (nx>=0 && ny>=0 && nx<rows && ny<cols && !seen[nx][ny]){ //未访问位置dist[nx][ny] = dist[cur.first][cur.second]+1; //更新距离q.push({nx,ny});seen[nx][ny]=1; //标记为访问过}}}int res=0; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++){if(dist[i][j]>res)res=dist[i][j];}return res;}
};