3
static int[][] DIRECTION = new int[][] {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};8
public int[][] highestPeak(int[][] isWater) {9
this.isWater = isWater;10
rows = isWater.length;11
cols = isWater[0].length;13
int[][] heightCells = new int[rows][cols];15
// store the coordinate of water cell16
Queue<int[]> queue = new LinkedList();18
for (int r = 0; r < rows; r++) {19
for (int c = 0; c < cols; c++) {20
if (isWater[r][c] == 1) {23
heightCells[r][c] = 0;25
// add water coordinate26
queue.add(new int[] {r, c});28
// mark default value for land29
heightCells[r][c] = -1;36
* 1. start from every water source,37
update their neighbor height38
* 2. add each neighbours which was not processed earlier39
3. do it every cell is processed41
bfs(queue, heightCells);46
private void bfs(Queue<int[]> queue, int[][] heightCells) {48
while (!queue.isEmpty()) {49
int[] cell = queue.remove();51
// increment height of neighbor cell in all 4 direction52
// e.g, left, right, up, down53
for (int[] dir : DIRECTION) {55
int newRow = cell[0] + dir[0];56
int newCol = cell[1] + dir[1];58
// check new coordinate of cell inside the grid or not59
if (!isInsideGrid(newRow, newCol)) continue;61
// check already handled62
if (heightCells[newRow][newCol] != -1) continue;65
heightCells[newRow][newCol] = heightCells[cell[0]][cell[1]] + 1;67
// to handle the neighbour of this new cell68
queue.add(new int[] {newRow, newCol});73
private boolean isInsideGrid(int row, int col) {74
return row >= 0 && row < rows && col >= 0 && col < cols;