You are given a matrix isWater
of size m x n
where:
isWater[i][j] == 0
: This cell represents land.isWater[i][j] == 1
: This cell represents water.The input specifies where water
and land
cells are located, but it does not specify the heights
of the land cells. Your task is to assign heights to the land cells following these rules
:
0
.1
. This ensures a smooth gradient of heights between neighboring cells.Your goal is to return a matrix height
of size m x n
where height[i][j]
represents the height of cell (i, j)
while following the rules.
Input:
isWater = [[0,1], [0,0]]
Output:
height = [[1,0], [2,1]]
Explanation:
(0,1)
has height 0
(rule #1).(0,0)
and (1,1)
have heights 1
and 1
, differing by exactly 1
(rule #2).(1,0)
has height 2
, which is the highest possible height while meeting the adjacency rule (rule #3).Input:
isWater = [[0,0,1], [1,0,0], [0,0,0]]
Output:
height = [[1,1,0], [0,1,1], [1,2,2]]
Explanation:
(0,2)
and (1,0)
have height 0
.2
.1.Initialization:
Start by creating the height
matrix where all cells are initially unassigned. Assign 0
to all water cells since water must have height 0
.
height = 0
) simultaneously.
1
more than the current cell’s height.height
matrix will be filled, and the maximum height will naturally be achieved.0
) for spreading heights to the surrounding land.1 <= m, n <= 1000
.isWater
contains at least one 1
).This ensures the solution is efficient and scalable for large inputs.
Loading component...
Loading component...
Main Function is not defined.
INPUT: isWater = [[0,1], [0,0]]
OUTPUT: height = [[1,0], [2,1]]
public static int[][] highestPeak(int[][] isWater) {
int m = isWater.length;
int n = isWater[0].length;
int[][] height = new int[m][n];
for(int[] row : height) {
Arrays.fill(row , -1);
}//Loop End
Queue<int[]> queue = new LinkedList<>();
for(int i = 0; i < m; i++) {
for(int j =0; j < n; j++){
if(isWater[i][j] == 1) {
height[i][j] = 0;
queue.offer(new int[]{i , j});
}//If End
}//Loop End
}//Loop End
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
while (!queue.isEmpty()) {
int[] cell = queue.poll();
int x = cell[0], y = cell[1];
for (int[] dir : directions) {
int nx = x + dir[0];
int ny = y + dir[1];
if (nx >= 0 && nx < m && ny >= 0 && ny < n && height[nx][ny] == -1) {
height[nx][ny] = height[x][y] + 1;
queue.offer(new int[]{nx, ny});
}//If End
}//Loop End
}//Loop End
return height;
}//function end
Utility Function is not required.