You are given an integer matrix isWater
of size m x n
that represents a map of land and water cells.
isWater[i][j] == 0
, cell (i, j)
is a land cell.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:
0
.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]
is 0
or 1
.题目链接:https://leetcode.com/problems/map-of-highest-peak/
题目大意:n*m的矩阵,水的高度为0,地的高度大于0,且要求相邻两个高度差不能超过1,求一种排列方式使得其中的最大值最大
题目分析:多源点bfs,将水的位置都作为源点,每次向四个方向扩散,高度加1,开始一直在想这么做有没有可能出现违反高度差不超过1的限制。其实是不可能的,因为bfs是用队列维护的,特点是先进先出,换句话说,假设当前队首的高度为h,队尾的高度为h+1,不可能出现队尾高度仍为h但队尾高度为h+2的情况,因为处理h+2的前提是所有高度为h的都已处理完毕
65ms,时间击败91.58%
class Solution {
final int[] dx = new int[] {0, 1, 0, -1};
final int[] dy = new int[] {1, 0, -1, 0};
public int[][] highestPeak(int[][] isWater) {
int n = isWater.length, m = isWater[0].length;
int[][] dp = new int[n][m];
Queue q = new LinkedList<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (isWater[i][j] == 1) {
dp[i][j] = 0;
q.offer(new int[] {i, j});
} else {
dp[i][j] = -1;
}
}
}
while (!q.isEmpty()) {
int[] cur = q.poll();
for (int k = 0; k < 4; k++) {
int x = cur[0] + dx[k];
int y = cur[1] + dy[k];
if (x >= 0 && y >= 0 && x < n && y < m && dp[x][y] == -1) {
dp[x][y] = dp[cur[0]][cur[1]] + 1;
q.offer(new int[] {x, y});
}
}
}
return dp;
}
}