CC189 - 1.7

1.7 Rotate Matrix: Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?

bool rotateSquare(vector<vector<int>> &matrix){
    if(matrix.size()==0 || matrix[0].size()!=matrix.size()) return false;
    int n = matrix.size();
    for(int layer=0;layer<n/2;layer++){
        int first = layer;
        int last = n-layer-1;
        for(int i=first;i<last;i++){
            int offset = i-first;
            int temp = matrix[first][i];
            matrix[first][i] = matrix[i][last];
            matrix[i][last] = matrix[last][last-offset];
            matrix[last][last-offset] = matrix[last-offset][first];
            matrix[last-offset][first] = temp;
        }
    }
    return true;
}

https://onlinegdb.com/S1Ojlj0jV

猜你喜欢

转载自blog.csdn.net/real_lisa/article/details/89918815
1.7