161. Rotate Image

Code(Language:C++) (Judger:cloudjudge-cluster-5)
class Solution {
public:
    /**
     * @param matrix: a lists of integers
     * @return: nothing
     */
    void rotate(vector<vector<int>> &matrix) {
        // write your code here
        const int n = matrix.size();
        if(n <= 1){
            return; 
        }
        int cnt = 0; 
        // (n - 1, 0) -> (0, 0); (n - 1, n - 1) -> (n - 1, 0); (0, n - 1) -> (n - 1, n - 1); (0, 0) -> (0, n - 1); 
        while((cnt + 1) * 2 <= n){
            for(int j = cnt; j < n - cnt - 1; j++){ //注意这里,不是n - cnt, 一行的最后一个不用处理
               int tmp = matrix[cnt][j];
               matrix[cnt][j] = matrix[n - 1 - j][cnt];
               matrix[n - 1 - j][cnt] = matrix[n - 1 - cnt][n - 1 - j]; 
               matrix[n - 1 - cnt][n - 1 - j] = matrix[j][n - 1 - cnt]; 
               matrix[j][n - 1 - cnt] = tmp; 
            }
            cnt++; 
        }
        return; 
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

Comments

Popular posts from this blog

算法的比较