Map of Highest Peak LeetCode solution in Java

1
class Solution {
2

3
static int[][] DIRECTION = new int[][] {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
4
int rows;
5
int cols;
6
int[][] isWater;
7

8
public int[][] highestPeak(int[][] isWater) {
9
this.isWater = isWater;
10
rows = isWater.length;
11
cols = isWater[0].length;
12

13
int[][] heightCells = new int[rows][cols];
14

15
// store the coordinate of water cell
16
Queue<int[]> queue = new LinkedList();
17

18
for (int r = 0; r < rows; r++) {
19
for (int c = 0; c < cols; c++) {
20
if (isWater[r][c] == 1) {
21

22
// mark as water
23
heightCells[r][c] = 0;
24

25
// add water coordinate
26
queue.add(new int[] {r, c});
27
} else {
28
// mark default value for land
29
heightCells[r][c] = -1;
30
}
31
}
32
}
33

34
/*
35
* Approach
36
* 1. start from every water source,
37
update their neighbor height
38
* 2. add each neighbours which was not processed earlier
39
3. do it every cell is processed
40
*/
41
bfs(queue, heightCells);
42

43
return heightCells;
44
}
45

46
private void bfs(Queue<int[]> queue, int[][] heightCells) {
47

48
while (!queue.isEmpty()) {
49
int[] cell = queue.remove();
50

51
// increment height of neighbor cell in all 4 direction
52
// e.g, left, right, up, down
53
for (int[] dir : DIRECTION) {
54

55
int newRow = cell[0] + dir[0];
56
int newCol = cell[1] + dir[1];
57

58
// check new coordinate of cell inside the grid or not
59
if (!isInsideGrid(newRow, newCol)) continue;
60

61
// check already handled
62
if (heightCells[newRow][newCol] != -1) continue;
63

64
// increament,
65
heightCells[newRow][newCol] = heightCells[cell[0]][cell[1]] + 1;
66

67
// to handle the neighbour of this new cell
68
queue.add(new int[] {newRow, newCol});
69
}
70
}
71
}
72

73
private boolean isInsideGrid(int row, int col) {
74
return row >= 0 && row < rows && col >= 0 && col < cols;
75
}
76
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0