【leetcode】48.Rotate Imageキューブマトリクスを時計回りに90°回転
1.テーマ
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:Could you do this in-place?
2.考え方
最外層の正方形のエッジを回転させるたびに、N/2回反復して層ごとに全体を回転させます.各正方形の回転は、エッジの各ノード(最後のノードを除く)をトップエッジで巡回し、現在の正のエッジ型の左上の頂点を持つ内の正のエッジ型の4つの頂点を回転します.
3.コード
時間:6 ms
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:Could you do this in-place?
2.考え方
最外層の正方形のエッジを回転させるたびに、N/2回反復して層ごとに全体を回転させます.各正方形の回転は、エッジの各ノード(最後のノードを除く)をトップエッジで巡回し、現在の正のエッジ型の左上の頂点を持つ内の正のエッジ型の4つの頂点を回転します.
3.コード
時間:6 ms
class Solution {
public:
// matrix , (N-2)*(N-2) matrix 。
// 4 。
// : 。
void rotate(vector>& matrix) {
int N = matrix.size();
for (int i = 0; i < N/2; i++) {
rotate(matrix, i);
}
return ;
}
// [lt,lt]
void rotate(vector>& matrix, int lt) {
int N = matrix.size();
if (lt >= N/2) {
return ;
}
// N - 2*lt, , ( )
int beg = lt;
int end = N - lt - 1;
for (int i = beg; i < end; i++) {
int pos[4][2]; // / / /
pos[0][0] = lt;
pos[0][1] = i;
pos[1][0] = i;
pos[1][1] = N-lt-1;
pos[2][0] = N-lt-1;
pos[2][1] = N-i-1;
pos[3][0] = N-i-1;
pos[3][1] = lt;
//
int tmp = matrix[pos[0][0]][pos[0][1]];
matrix[pos[0][0]][pos[0][1]] = matrix[pos[3][0]][pos[3][1]];
matrix[pos[3][0]][pos[3][1]] = matrix[pos[2][0]][pos[2][1]];
matrix[pos[2][0]][pos[2][1]] = matrix[pos[1][0]][pos[1][1]];
matrix[pos[1][0]][pos[1][1]] = tmp;
}
return ;
}
};