LeetCode.1861 Rotating the Box(旋转箱子)

1.题目

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.

2.样例

  • 样例1
Input: box = [["#",".","#"]]
Output: [["."],
         ["#"],
         ["#"]]
  • 样例2
Input: box = [["#",".","*","."],
              ["#","#","*","."]]
Output: [["#","."],
         ["#","#"],
         ["*","*"],
         [".","."]]
  • 样例3
Input: box = [["#","#","*",".","*","."],
              ["#","#","#","*",".","."],
              ["#","#","#",".","#","."]]
Output: [[".","#","#"],
         [".","#","#"],
         ["#","#","*"],
         ["#","*","."],
         ["#",".","*"],
         ["#",".","."]]

3.题解

  • 描述:题目的意思是对箱子(二维数组)进行顺时针旋转90度,其中单元格中的石头因为重力的原因下落,在碰到障碍时就停下了。否则就一直下落指导箱底。
  • 题解:
class Solution {
    public static char[][] rotateTheBox(char[][] box) {
        // 思路:从右往的遍历,统计碰到的empty的个数,直到遇到stone后重新清零,最后将整个数据旋转90即可
        if (box == null || box[0] == null || box[0].length == 0) {
            return new char[0][];
        }

        char empty = '.';
        char obstacle = '*';
        char stone = '#';

        int m = box.length;
        int n = box[0].length;
        for (int i = 0; i < m; i++) {
            int emptyCount = 0;
            for (int j = n - 1; j >= 0; j--) {
                if (box[i][j] == empty) {
                    emptyCount++;
                } else if (box[i][j] == stone) {
                    box[i][j] = empty;
                    box[i][j + emptyCount] = stone;
                } else if (box[i][j] == obstacle) {
                    emptyCount = 0;
                }
            }
        }

        // 旋转数组,从下往上每行竖直(从左往右竖直)
        char[][] res = new char[n][m];
        for (int i = m - 1; i >= 0; i--) {
            for (int j = 0; j < n; j++) {
                res[j][m - 1 - i] = box[i][j];
            }
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值