• + 0 comments

    C++

    void matrixRotation(vector<vector<int>> matrix, int r) {
        int mr = matrix.size();
        int mc = matrix[0].size();
        int dirx[4] = {0, 1, 0, -1}; // x, y
        int diry[4] = {1, 0, -1, 0};
        vector<vector<int>>ring; // drul
        int num_ring = min(ceil(mr / 2), ceil(mc / 2));
        for(int i = 0; i < num_ring; i++){
            int sx = i, sy = i;
            int dir = 0, current_ring_num = 2 * mc + 2 * mr - 8 * i - 4;
            vector<int> tmp;
            for(int j = 0; j < current_ring_num; j++){
                if(sx + dirx[dir] >= mc - i || sy + diry[dir] >= mr - i || sy + diry[dir] < i){
                    dir++;
                }
                tmp.push_back(matrix[sy][sx]);
                sx += dirx[dir];
                sy += diry[dir];
            }
            rotate(tmp.begin(), tmp.end() - r % current_ring_num, tmp.end());
            ring.push_back(tmp);
        }
        for(int i = 0; i < ring.size(); i++){
            int sx = i, sy = i;
            int dir = 0, current_ring_num = 2 * mc + 2 * mr - 8 * i - 4;
            for(int j = 0; j < current_ring_num; j++){
                if(sx + dirx[dir] >= mc - i || sy + diry[dir] >= mr - i || sy + diry[dir] < i){
                    dir++;
                }
                matrix[sy][sx] = ring[i][j];
                sx += dirx[dir];
                sy += diry[dir];
            }
        }
        for(int i = 0; i < matrix.size(); i++){
            for(int j = 0; j < matrix[i].size(); j++)
                cout<<matrix[i][j]<<" ";
            cout<<endl;
        }
    }