1765. Map of Highest Peak

T: O(mn)
S:O(2m+2n result mn) 
```java
class Solution {
    class Step {
        int x;
        int y;
        int level;
        Step(int x, int y, int level) {
            this.x = x;
            this.y = y;
            this.level = level;
        }
    }
    private static final int[][] DIRS = {{0,1}, {1,0}, {0,-1}, {-1,0}};
    public int[][] highestPeak(int[][] isWater) {
        int m = isWater.length;
        int n = isWater[0].length;
        int[][] result = new int[m][n];
        for (int i = 0; i < m; i++) {
            Arrays.fill(result[i], -1); // means not visited
        }

        Queue<Step> queue = new LinkedList<>();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (isWater[i][j] == 1) {
                    queue.offer(new Step(i, j, 0));
                }
            }
        }

        while (!queue.isEmpty()) {
            Step cur = queue.poll();
            if (result[cur.x][cur.y] != -1) {
                continue;
            } 
            result[cur.x][cur.y] = cur.level;
            
            for (int[] dir : DIRS) {
                int x = cur.x + dir[0];
                int y = cur.y + dir[1];
                if (x < 0 || x >= m || y < 0 || y >= n) {
                    continue;
                }
                queue.offer(new Step(x, y, cur.level+1));
            }
        }
        return result;
    }
}

/*
use BFS from water
fill out level to cells -> it's the ans

T: O(mn)
S:O(2m+2n result mn) // no need visited, use -1 to check

every time we go 4 dirs, so it can expand normally

考慮是不是需要用 visited
本題可用可不用, 反正結果是獨立一個空間出來的
*/
```

Last updated