โ† All problems

1765. Map of Highest Peak

MediumOpen on LeetCodeProblem statement

Problem Statement

1765. Map of Highest Peak

Medium


You are given an integer matrix isWater of size m x n that represents a map of land and water cells.

You must assign each cell a height in a way that follows these rules:

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:

 

Note: This question is the same as 542: https://leetcode.com/problems/01-matrix/

Java โ€” bfs floodFill

Source file
class Solution {
    public int[][] highestPeak(int[][] isWater) {
        int[][] dirs = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };
        int m = isWater.length, n = isWater[0].length;
        int[][] ht = new int[m][n];
        boolean[][] vis = new boolean[m][n];
        for (int[] r : ht)
            Arrays.fill(r, -1);
        Queue<Pair<Integer, Integer>> q = new LinkedList<>();
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (isWater[i][j] == 1)
                    q.add(new Pair<>(i, j));
        int currHt = 0;
        while (!q.isEmpty()) {
            int size = q.size();
            while (size-- > 0) {
                Pair<Integer, Integer> p = q.remove();
                int i = p.getKey(), j = p.getValue();
                if (vis[i][j])
                    continue;
                ht[i][j] = currHt;
                vis[i][j] = true;
                for (int[] d : dirs) {
                    int I = i + d[0], J = j + d[1];
                    if (I >= 0 && J >= 0 && I < m && J < n)
                        q.add(new Pair<>(I, J));
                }
            }
            currHt++;
        }
        return ht;
    }
}