LeetCode in Kotlin

2536. Increment Submatrices by One

Medium

You are given a positive integer n, indicating that we initially have an n x n 0-indexed integer matrix mat filled with zeroes.

You are also given a 2D integer array query. For each query[i] = [row1i, col1i, row2i, col2i], you should do the following operation:

Return the matrix mat after performing every query.

Example 1:

Input: n = 3, queries = [[1,1,2,2],[0,0,1,1]]

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

Explanation: The diagram above shows the initial matrix, the matrix after the first query, and the matrix after the second query.

Example 2:

Input: n = 2, queries = [[0,0,1,1]]

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

Explanation: The diagram above shows the initial matrix and the matrix after the first query.

Constraints:

Solution

class Solution {
    fun rangeAddQueries(n: Int, queries: Array<IntArray>): Array<IntArray> {
        val g = Array(n) { IntArray(n) }
        for (q in queries) {
            val r1 = q[0]
            val c1 = q[1]
            val r2 = q[2]
            val c2 = q[3]
            g[r1][c1]++
            if (c2 < n - 1) {
                g[r1][c2 + 1]--
            }
            if (r2 < n - 1) {
                g[r2 + 1][c1]--
            }
            if (c2 < n - 1 && r2 < n - 1) {
                g[r2 + 1][c2 + 1]++
            }
        }
        for (i in 0 until n) {
            for (j in 0 until n) {
                if (i > 0) {
                    g[i][j] += g[i - 1][j]
                }
                if (j > 0) {
                    g[i][j] += g[i][j - 1]
                }
                if (i > 0 && j > 0) {
                    g[i][j] -= g[i - 1][j - 1]
                }
            }
        }
        return g
    }
}