給定一個(gè) *n *× n 的二維矩陣表示一個(gè)圖像泪幌。
將圖像順時(shí)針旋轉(zhuǎn) 90 度肴焊。
說明:
你必須在原地旋轉(zhuǎn)圖像其屏,這意味著你需要直接修改輸入的二維矩陣唧瘾。請(qǐng)不要使用另一個(gè)矩陣來旋轉(zhuǎn)圖像翔曲。
示例 :
給定 matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
原地旋轉(zhuǎn)輸入矩陣,使其變?yōu)?
[
[7,4,1],
[8,5,2],
[9,6,3]
]
給定 matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
原地旋轉(zhuǎn)輸入矩陣劈愚,使其變?yōu)?
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
思路:
- 本題較為簡(jiǎn)單,主要考察循環(huán)體與邊界值處理
- 由于90度旋轉(zhuǎn),每個(gè)數(shù)字對(duì)應(yīng)旋轉(zhuǎn)四個(gè)位置,例如例1中的 1,7,9,3四個(gè)角落數(shù)字旋轉(zhuǎn)之后的對(duì)應(yīng)關(guān)系為7,9,3,1
- 設(shè)置對(duì)應(yīng)關(guān)系,如下:
其中i為行數(shù),j為列數(shù)
起始位置:matrix[i][j]
逆時(shí)針90度位置:
matrix[lenh - j - 1][i]
逆時(shí)針180度位置:
matrix[lenw- i- 1][lenh- j- 1]
逆時(shí)針270度位置:
matrix[j][lenw - i - 1]
- 由于該對(duì)應(yīng)關(guān)系將數(shù)字分為了四組,每行變換的起始位置與末尾位置都有不同,需特別注意j的取值范圍
代碼:
public void rotate(int[][] matrix) {
int lenw = matrix.length;
if(lenw == 0) return ;
int lenh = matrix[0].length;
int k = lenw,temp;
for(int i = 0;i < lenh/2;i++) {
for(int j = i;j < k-1;j++) {
temp = matrix[i][j];
matrix[i][j] = matrix[lenh - j - 1][i];
matrix[lenh - j - 1][i] = matrix[lenw- i- 1][lenh- j- 1];
matrix[lenw- i- 1][lenh- j- 1] = matrix[j][lenw - i - 1];
matrix[j][lenw - i - 1] = temp;
}
k--;
}
return ;
}
總結(jié):
- 在各類原地?cái)?shù)組變換題中,不同解法的對(duì)應(yīng)關(guān)系的設(shè)置非常重要,需要確保無誤才能進(jìn)行下一步
- 注意循環(huán)體邊界的變化
- 題目一變難基本靠抄,日子沒法過了qwq