05 August 2008
顺时针旋转盒子90度,让本来在其中的物品因为重力改变位置
After rotating the array 90°, the right hand side will be the bottom.
For each row:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
empty will point to the last cell that is empty. Initially empty = columns - 1.
Start from last column in the row, for each column c:
if current cell contains a stone, we will move it from current cell to the empty cell(which is represented by empty variable).
if current cell contains an obstacle, we will change value of empty to c-1.
After customising the array box, we will create another array box2 which will be rotated version of box. ```java class Solution {
public char[][] rotateTheBox(char[][] box) {
int r = box.length, c = box[0].length;
char[][] box2 = new char[c][r];
for(int i = 0; i<r; ++i){
int empty = c-1;
for(int j = c-1; j>=0; --j){
if(box[i][j] == '*'){
empty = j-1;
}
if(box[i][j] == '#'){
box[i][j] = '.';
box[i][empty] = '#';
--empty;
}
}
}
for(int i = 0; i<r; ++i){
for(int j = c-1; j>=0; --j)
box2[j][r-i-1] = box[i][j];
}
return box2;
} } ```
Java8 two pointers
1
2
3
4
5
6
7
8
9
10
11
12
13
public char[][] rotateTheBox(char[][] box) {
int m = box.length, n = box[0].length;
char [][] res = new char[n][m];
for (int i = 0; i < m; ++i)
for (int j = n - 1, k = n - 1; j >= 0; --j) {
res[j][m - i - 1] = '.';
if (box[i][j] != '.') {
k = box[i][j] == '*' ? j : k;
res[k--][m - i - 1] = box[i][j];
}
}
return res;
}