LeetCode in Kotlin

1861. Rotating the Box

Medium

You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the box is one of the following:

The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles’ positions, and the inertia from the box’s rotation does not affect the stones’ horizontal positions.

It is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the box.

Return an n x m matrix representing the box after the rotation described above.

Example 1:

Input:

box = \[\["#",".","#"]]

Output:

[["."], 
 ["#"], 
 ["#"]]

Example 2:

Input:

box = \[\["#",".","*","."], 
       ["#","#","*","."]]

Output:

[["#","."], 
 ["#","#"], 
 ["*","*"], 
 [".","."]]

Example 3:

Input:

box = \[\["#","#","*",".","*","."], 
       ["#","#","#","*",".","."], 
       ["#","#","#",".","#","."]]

Output:

[[".","#","#"], 
 [".","#","#"], 
 ["#","#","*"], 
 ["#","*","."], 
 ["#",".","*"], 
 ["#",".","."]]

Constraints:

Solution

class Solution {
    fun rotateTheBox(box: Array<CharArray>): Array<CharArray> {
        val n = box.size
        val m = box[0].size
        val result = Array(m) { CharArray(n) }
        for (i in 0 until n) {
            var j = m - 1
            var idx = m - 1
            while (j >= 0) {
                if (box[i][j] == '#') {
                    result[j--][n - i - 1] = '.'
                    result[idx--][n - i - 1] = '#'
                } else {
                    val c = box[i][j]
                    result[j--][n - i - 1] = c
                    if (c == '*') {
                        idx = j
                    }
                }
            }
        }
        return result
    }
}
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