48. Rotate Image (Matrix)
https://leetcode.com/problems/rotate-image/discuss/159913/found-a-general-method
刚发现一个套路了,对于这类matrix翻转的题目,一般都是经过一个中间过渡状态,比如:
1,2,3
4,5,6
7,8,9
要变成:
7,4,1
8,5,2
9,6,3
需要经过:
1,4,7
2,5,8
3,6,9
也就是把第一行变成第一列,第二行变成第二列。。。
然后以中间为轴,左右翻转,666吧?
1 class Solution { 2 public void rotate(int[][] matrix) { 3 if(matrix == null || matrix.length == 0 || matrix[0].length == 0) { 4 return; 5 } 6 int row = matrix.length; 7 int col = matrix[0].length; 8 for(int i = 0; i < row; i++) { 9 for(int j = i; j < col; j++) { 10 int temp = matrix[i][j]; 11 matrix[i][j] = matrix[j][i]; 12 matrix[j][i] = temp; 13 } 14 } 15 16 for(int i = 0; i < row; i++) { 17 for(int j = 0; j < col / 2; j++) { 18 int temp = matrix[i][j]; 19 matrix[i][j] = matrix[i][col-1-j]; 20 matrix[i][col-1-j] = temp; 21 } 22 } 23 } 24 }