阅读视图

发现新文章,点击刷新页面。

1861. 遍历一行填充一列

解题思路

我不明白为什么官方题解写的那么复杂,旋转前第 $i$ 行对应旋转后 $m-1-i$ 列,然后我们用一个 $idx$ 指针遍历旋转前第 $i$ 行的每一个元素,用一个变量 $stones$ 统计每段石头的数量,遇到障碍或结尾就开始把结果填充到 $m-1-i$ 列对应的位置 $[idx-stones,:idx)$,当然还要记得设置 $ans[idx][m-1-i]$ 为障碍物,然后循环执行上述操作直到这行遍历结束。
图片解说如下:
LC1861.png

代码

###C++

class Solution {
public:
    vector<vector<char>> rotateTheBox(vector<vector<char>>& box) {
        const int m = (int)box.size(), n = (int)box[0].size();
        vector<vector<char>>ans(n,vector<char>(m,'.'));
        for (int i = 0; i < m; ++i) {
            int idx = 0;
            while (idx < n) {
                int stones = 0;
                while (idx < n && box[i][idx] != '*') {
                    if (box[i][idx] == '#') {
                        stones++;
                    }
                    idx++;
                }
                //fill stones into ans column m-1-i and rows range [idx-stones,idx)
                for (int j = idx - stones; j < idx; ++j) {
                    ans[j][m - 1 - i] = '#';
                }
                //fill obstacle into ans[idx][m-1-i]
                if (idx < n) {
                    ans[idx][m - 1 - i] = '*';
                }
                idx++;
            }
        }
        return ans;
    }
};

###Java

class Solution {
    public char[][] rotateTheBox(char[][] box) {
        int m = box.length, n = box[0].length;
        char[][] ans = new char[n][m];
        for(char[] row : ans){
            Arrays.fill(row, '.');
        }
        for (int i = 0; i < m; ++i) {
            int idx = 0;
            while (idx < n) {
                int stones = 0;
                while (idx < n && box[i][idx] != '*') {
                    if (box[i][idx] == '#') {
                        stones++;
                    }
                    idx++;
                }
                //fill stones into ans column m-1-i and rows range [idx-stones,idx)
                for (int j = idx - stones; j < idx; ++j) {
                    ans[j][m - 1 - i] = '#';
                }
                //fill obstacle into ans[idx][m-1-i]
                if (idx < n) {
                    ans[idx][m - 1 - i] = '*';
                }
                idx++;
            }
        }
        return ans;
    }
}
❌