1861. Rotating the Box

54 阅读1分钟

image.png

image.png

方法

  • 从后往前遍历每一行:
    • 当遍历到一块挡板时,下一个可放石头的位置可能是前一个位置;
    • 当我们遍历到一个石头,把石头放在前一个空位,然后更新指针
class Solution {
    public char[][] rotateTheBox(char[][] box) {
        int m = box.length, n = box[0].length;

        for (int i = 0; i < m; i ++) {
            int emptyIdx = n - 1; // 当前可放石头的空位
            // 从后往前扫
            for (int j = n - 1; j >= 0; j--) {
                if (box[i][j] == '*') {
                    emptyIdx = j - 1; // 阻碍物的前一位,是下一个可放石头的空位
                } else if (box[i][j] == '#') {
                    box[i][j] = '.'; // 挪走石头
                    box[i][emptyIdx] = '#'; //放到空位
                    emptyIdx--; // 空位index更新
                }
            }
        }

        // 顺时针旋转90
        char[][] res = new char[n][m];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                res[j][m - i - 1] = box[i][j];
            }
        }

        return res;
    }
}