标签:c style class blog code java
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?
实现题。从最外圈顺时针交换,最多交换n/2圈就行。
1 class Solution { 2 public: 3 void rotate(vector<vector<int> > &matrix) { 4 int n = matrix.size(); 5 int tmp; 6 // 这个row其实就是圈数,最后中间可能会剩下一个点,这个点不需要旋转,无碍 7 for (int row = 0; row < n / 2; ++row) { 8 9 // 这里是要注意,每一圈的每一边,最后一个数是不用处理的,不然就多做了一遍了。所以这里i是到n- 2* row - 1而不是n - 2*row 10 for (int i = 0; i < n - 2 * row - 1; i++) { 11 tmp = matrix[row][row + i]; 12 matrix[row][row + i] = matrix[n - row - i - 1][row]; 13 matrix[n - row - i - 1][row] = matrix[n - row - 1][n - row - i - 1]; 14 matrix[n - row - 1][n - row - i - 1] = matrix[row + i][n - row - 1]; 15 matrix[row + i][n - row - 1] = tmp; 16 } 17 } 18 } 19 };
Leetcode | Rotate Image,布布扣,bubuko.com
标签:c style class blog code java
原文地址:http://www.cnblogs.com/linyx/p/3773742.html