zoukankan      html  css  js  c++  java
  • Leetcode 1861. 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:

    • A stone '#'
    • A stationary obstacle '*'
    • Empty '.'

    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:

    • m == box.length
    • n == box[i].length
    • 1 <= m, n <= 500
    • box[i][j] is either '#''*', or '.'.

     【题目分析】

    将一个矩阵顺时针旋转90度,矩阵中的石头在重力的牵引下向下掉落,直到遇到障碍物或者其他石块。

    注意:

    1. 矩阵是顺时针旋转,不是矩阵的转置。因此变换关系为,res[j][m-1-i] = box[i][j],m = box.length.

    【思路分析】

    创建一个新矩阵,为新矩阵的每一列从下往上赋值,这个过程中有一个指针,一个记录经过变化后当前元素应该落在哪个位置,一个记录由于重力原因,该元素实际应该放置的位置。

    【Java代码】

    class Solution {
        public char[][] rotateTheBox(char[][] box) {
            int m = box.length, n = box[0].length;
            char[][] res = new char[n][m];
            for(int i = 0; i < m; i++) {
                for(int j = n-1, k = n-1; j >= 0; j--) {
                    res[j][m-1-i] = '.';
                    if(box[i][j] != '.') {
                        if(box[i][j] == '*') {
                            k = j;
                        }
                        res[k--][m-1-i] = box[i][j];
                    }
                }
            }
            return res;
        }
    }
    
  • 相关阅读:
    用POP动画模拟真实秒钟摆动效果
    解析苹果的官方例子LazyTableImages实现图片懒加载原理
    支持xcode6的缓动函数Easing以及使用示例
    [转] iOS 动画库 Pop 和 Canvas 各自的优势和劣势是什么?
    NSJSONSerialization能够处理的JSONData
    [翻译] USING GIT IN XCODE [6] 在XCODE中使用GIT[6]
    [翻译] USING GIT IN XCODE [5] 在XCODE中使用GIT[5]
    [翻译] USING GIT IN XCODE [4] 在XCODE中使用GIT[4]
    [翻译] USING GIT IN XCODE [3] 在XCODE中使用GIT[3]
    【转】断点继传
  • 原文地址:https://www.cnblogs.com/liujinhong/p/14801517.html
Copyright © 2011-2022 走看看