解题思路:
1.找到水的位置,入队,带出第一层的高度。
2.任意相邻的格子高度差 至多 为 1,
通过当前节点带出相邻格子的高度,然后把相邻格子入队;
3.不断地执行此过程直到队列为空; 也就是由点到面铺开计算。
代码:
class Solution
{
public:
int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
vector<vector<int>> highestPeak(vector<vector<int>> &isWater)
{
int row = isWater.size();
int col = isWater[0].size();
vector<vector<int>> ans(row, vector<int>(col, -1)); // -1 表示该格子尚未被访问过
queue<pair<int, int>> q; //辅助队列
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
{
if (isWater[i][j])
{
ans[i][j] = 0;
q.push(make_pair(i,j)); // 将所有水域入队
}
}
}
while (!q.empty())
{
int sz = q.size();
while(sz--)
{
int t_row = q.front().first;
int t_col = q.front().second;
q.pop();
for (int i = 0; i < 4; ++i) //四个方位
{
int new_row = t_row + dir[i][0];
int new_col = t_col + dir[i][1];
if (new_row < 0 || new_row >= row || new_col < 0 || new_col >= col
||ans[new_row][new_col] != -1)
{
continue; //如果位置越界,访问过,则跳过
}
ans[new_row][new_col] = ans[t_row][t_col] + 1;
q.push(make_pair(new_row,new_col));
}
}
}
return ans;
}
};