https://leetcode.com/problems/rotating-the-box/description/
1861. Rotating the Box
給你一個字元陣列表示一個箱子
# 表示石頭
* 表示地板
. 表示空氣
求出我們把箱子往右翻轉90度之後石頭的分布狀況,如果石頭下面是空氣會往下掉。
思路:
1.模擬解,先找到箱子翻轉前的地板座標,從這個座標往上數直到碰到其他牆壁或越界
,找出地板上面有幾個石頭,然後在翻轉後的箱子上面堆疊。
2.注意一個行完全沒地板的corner case就好。
java code
-----------------------------------------
class Solution {
public char[][] rotateTheBox(char[][] box) {
int m = box.length;
int n = box[0].length;
char[][] res = new char[n][m];
for (int i = 0; i < n; i++) {
Arrays.fill(res[i], '.');
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (box[i][j] == '*') {
res[j][m - 1 - i] = '*';
// 從(i,j)往左找,直到撞到其他障礙物或越界,找出該障礙物上
面共有幾個石頭
int stones = countStones(box, i, j);
putStones(res, j, m - 1 - i, stones);
}
}
}
// 最底層也可能有石頭
for (int i = 0; i < m; i++) {
int stones = countStones(box, i, n);
putStones(res, n, m - 1 -i, stones);
}
return res;
}
private int countStones(char[][] box, int y, int x) {
int res = 0;
for (int i = x - 1; i >= 0; i--) {
if (box[y][i] == '*') break;
else if (box[y][i] == '#') res++;
}
return res;
}
private void putStones(char[][] box, int y, int x, int stones) {
for (int i = 0; i < stones; i++) {
box[--y][x] = '#';
}
}
}
-----------------------------------------
--
https://i.imgur.com/5xKbxoh.jpeg
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.158.191.3 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1732348553.A.AD3.html