其他分享
首页 > 其他分享> > LeetCode 1861. Rotating the Box

LeetCode 1861. Rotating the Box

作者:互联网

原题链接在这里:https://leetcode.com/problems/rotating-the-box/

题目:

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:

题解:

Rotate 90 degree clockwise, res[i][j] = box[m - j - 1][i].

Then for each column, iterate from the bottom.

When hitting obstacle, cur position is decreased by 1. cur is the current position we could place stone.

If we encounter a stone, mark it as empty, then mark current position as stone.

Time Complexity: O(m * n). m = box.length. n = box[0].length.

Space: O(1). regardless res.

AC Java:

 1 class Solution {
 2     public char[][] rotateTheBox(char[][] box) {
 3         if(box == null || box.length == 0 || box[0].length == 0){
 4             return box;
 5         }
 6         
 7         int m = box.length;
 8         int n = box[0].length;
 9         char [][] res = new char[n][m];
10         for(int i = 0; i < n; i++){
11             for(int j = 0; j < m; j++){
12                 res[i][j] = box[m - j - 1][i];
13             }
14         }
15         
16         for(int j = 0; j < m; j++){
17             int cur = n - 1;
18             for(int i = n - 1; i >= 0; i--){
19                 if(res[i][j] == '*'){
20                     cur = i - 1;
21                 }else if(res[i][j] == '#'){
22                     res[i][j] = '.';
23                     res[cur--][j] = '#';
24                 }
25             }
26         }
27         
28         return res;
29     }
30 }

类似Rotate Image.

标签:Box,Rotating,stone,cur,int,res,box,1861,length
来源: https://www.cnblogs.com/Dylan-Java-NYC/p/16493690.html