LeetCode: Rotate Image

最开始还用了一种递归的方法。。。也不知道是聪明还是傻。

先将最外圈旋转,然后向里一圈,旋转。。。。最后到达矩阵中心。

这里比较麻烦的是矩阵的下标,调了好久才写对。

LeetCode: Rotate Image
 1 public static void rotate(int[][] matrix) {
 2         rotate(matrix, 0);
 3     }
 4     public static void rotate(int[][] matrix, int start) {
 5         if(start == matrix.length/2) return;
 6         int first=0, second=0, third=0, fourth=0;
 7         
 8         int row = matrix.length-1;
 9         int col = matrix.length-1;
10         
11         for(int i=start; i<col-start; i++) {
12             first = matrix[start][i];
13             second = matrix[i][col-start];
14             third = matrix[row-start][col-i];
15             fourth = matrix[row-i][start];
16             
17             int tmp1 = second;
18             matrix[i][col-start] = first;
19             int tmp2 = third;
20             matrix[row-start][col-i] = tmp1;
21             int tmp3 = fourth;
22             matrix[row-i][start] = tmp2;
23             matrix[start][i] = tmp3;
24         }
25         
26         rotate(matrix, start+1);
27     }
LeetCode: Rotate Image

 

LeetCode: Rotate Image
 1     void rotate(vector<vector<int> > &matrix) 
 2     {
 3         for (int i = 0, j = matrix.size()-1; i < j; i++, j--)
 4         {
 5             for (int k = i, d = j; k < j; k++, d--)
 6             {
 7                 int t = matrix[i][k];
 8                 matrix[i][k] = matrix[d][i];
 9                 matrix[d][i] = matrix[j][d];
10                 matrix[j][d] = matrix[k][j];
11                 matrix[k][j] = t;
12             }
13         }
14     }
LeetCode: Rotate Image

同一方法 别人写的。。。。感受一下。。。

网上一看,原来可以先转置,然后在将每一行的前后顺序调换就行了。。。这样思路就很清晰了。

LeetCode: Rotate Image
 1 public static void rotate1(int[][] matrix) {
 2         if (matrix.length == 0) return;
 3         transpose(matrix);
 4         int col = matrix.length;
 5         for(int i=0; i<col; i++) {
 6             for (int j=0; j<col/2; j++) {
 7                 int tmp = matrix[i][j];
 8                 matrix[i][j] = matrix[i][col-1-j];
 9                 matrix[i][col-1-j] = tmp;
10             }
11         }
12     }
13     
14     public static void transpose(int[][] matrix) {
15         for (int i=0; i<matrix.length; i++) {
16             for(int j=i; j<matrix[0].length; j++) {
17                 int tmp = matrix[i][j];
18                 matrix[i][j] = matrix[j][i];
19                 matrix[j][i] = tmp;
20             }
21         }
22     }
LeetCode: Rotate Image

LeetCode: Rotate Image

上一篇:如何自定义Grunt任务


下一篇:[LeetCode] Surrounded Regions, Solution