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.样例
Input: box = [["#",".","#"]]
Output: [["."],
["#"],
["#"]]
Input: box = [["#",".","*","."],
["#","#","*","."]]
Output: [["#","."],
["#","#"],
["*","*"],
[".","."]]
Input: box = [["#","#","*",".","*","."],
["#","#","#","*",".","."],
["#","#","#",".","#","."]]
Output: [[".","#","#"],
[".","#","#"],
["#","#","*"],
["#","*","."],
["#",".","*"],
["#",".","."]]
3.题解
- 描述:题目的意思是对箱子(二维数组)进行顺时针旋转90度,其中单元格中的石头因为重力的原因下落,在碰到障碍时就停下了。否则就一直下落指导箱底。
- 题解:
class Solution {
public static char[][] rotateTheBox(char[][] box) {
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;
}
}
|