LeetCode in Kotlin

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:

Solution

import java.util.LinkedList
import java.util.Queue

class Solution {
    private val dir = intArrayOf(0, 1, 0, -1, 0)

    fun highestPeak(isWater: Array<IntArray>): Array<IntArray> {
        var h = 1
        var q: Queue<IntArray> = LinkedList()
        for (i in isWater.indices) {
            for (j in isWater[0].indices) {
                isWater[i][j] = if (isWater[i][j] == 1) 0 else -1
                if (isWater[i][j] == 0) {
                    q.add(intArrayOf(i, j))
                }
            }
        }
        while (q.isNotEmpty()) {
            val q1: Queue<IntArray> = LinkedList()
            for (cur in q) {
                val x = cur[0]
                val y = cur[1]
                for (i in 0..3) {
                    val nx = x + dir[i]
                    val ny = y + dir[i + 1]
                    if (nx >= 0 && nx < isWater.size && ny >= 0 && ny < isWater[0].size && isWater[nx][ny] == -1) {
                        isWater[nx][ny] = h
                        q1.add(intArrayOf(nx, ny))
                    }
                }
            }
            h++
            q = q1
        }
        return isWater
    }
}