LeetCode in Kotlin

542. 01 Matrix

Medium

Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

Example 1:

Input: mat = [[0,0,0],[0,1,0],[0,0,0]]

Output: [[0,0,0],[0,1,0],[0,0,0]]

Example 2:

Input: mat = [[0,0,0],[0,1,0],[1,1,1]]

Output: [[0,0,0],[0,1,0],[1,2,1]]

Constraints:

Solution

class Solution {
    fun updateMatrix(mat: Array<IntArray>): Array<IntArray> {
        val dist = Array(mat.size) { IntArray(mat[0].size) }
        for (i in mat.indices) {
            dist[i].fill(Int.MAX_VALUE - 100000)
        }
        for (i in mat.indices) {
            for (j in mat[0].indices) {
                if (mat[i][j] == 0) {
                    dist[i][j] = 0
                } else {
                    if (i > 0) {
                        dist[i][j] = Math.min(dist[i][j], dist[i - 1][j] + 1)
                    }
                    if (j > 0) {
                        dist[i][j] = Math.min(dist[i][j], dist[i][j - 1] + 1)
                    }
                }
            }
        }
        for (i in mat.indices.reversed()) {
            for (j in mat[0].indices.reversed()) {
                if (i < mat.size - 1) {
                    dist[i][j] = Math.min(dist[i][j], dist[i + 1][j] + 1)
                }
                if (j < mat[0].size - 1) {
                    dist[i][j] = Math.min(dist[i][j], dist[i][j + 1] + 1)
                }
            }
        }
        return dist
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy