1765. Map of Highest Peak
You are given an integer matrix isWater
of size m x n
that represents a map of land and water cells.
- If
isWater[i][j] == 0
, cell(i, j)
is a land cell. - If
isWater[i][j] == 1
, cell(i, j)
is a water cell.
You must assign each cell a height in a way that follows these rules:
- The height of each cell must be non-negative.
- If the cell is a water cell, its height must be
0
. - Any two adjacent cells must have an absolute height difference of at most
1
. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).
Find an assignment of heights such that the maximum height in the matrix is maximized.
Return an integer matrix height
of size m x n
where height[i][j]
is cell (i, j)
's height. If there are multiple solutions, return any of them.
Example 1:
Input: isWater = [[0,1],[0,0]]
Output: [[1,0],[2,1]]
Explanation: The image shows the assigned heights of each cell.
The blue cell is the water cell, and the green cells are the land cells.
Example 2:
Input: isWater = [[0,0,1],[1,0,0],[0,0,0]]
Output: [[1,1,0],[0,1,1],[1,2,2]]
Explanation: A height of 2 is the maximum possible height of any assignment.
Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.
Constraints:
m == isWater.length
n == isWater[i].length
1 <= m, n <= 1000
isWater[i][j]
is0
or1
.- There is at least one water cell.
这个题,别想太多,就是按照以water点为中心,一层一层的填充,第一层填1,第二层填2,第三次填3....具体采用广度优先搜索的方式,用queue来保存填充过的那一层的点,然后循环即可。
一开始想多了,担心发生冲突,而实际上,一层一层的填,不会的,下面是采用刚才策略的模拟,到最后,都是沿着外围在生长填写。
附代码。
class Solution {
private:
vector<vector<int>> direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public:
vector<vector<int>> highestPeak(vector<vector<int>>& isWater) {
int row = isWater.size(), col = isWater[0].size();
vector<vector<int> > res(row, vector<int>(col, -1));
queue<pair<int, int>> helper;
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if(isWater[i][j] == 1){
helper.push(make_pair(i, j));
res[i][j] = 0;
}
}
}
while(!helper.empty()){
pair<int, int> temp = helper.front();
helper.pop();
for(int i = 0; i < 4; i++){
int x = temp.first + direction[i][0];
int y = temp.second + direction[i][1];
if(x >= 0 && x < row && y >= 0 && y < col && res[x][y] == -1){
res[x][y] = res[temp.first][temp.second] + 1;
helper.push(make_pair(x, y));
}
}
}
return res;
}
};