4ms ring by ring solution


  • 0
    P
    class Solution {
    public:
        void rotate(vector<vector<int>>& matrix) {
            	int nr = matrix.size() / 2; // number of rings to consider.
    	int prev, tmp;
    	
    	// Loop over the rings.
    	int cstart = 0;
    	int cend = matrix[0].size() - 1;
    	for(int r = 0; r < nr; r++)
    	{
    		// Loop over the columns
    		for(int c = cstart; c < cend; c++)
    		{
    			// First shift [r][c] go to [c][cend]
    			prev = matrix[c][cend];
    			matrix[c][cend] = matrix[r][c];
    
    			// Second shift [c][cend] go to [cend][cend-c +cstart]
    			tmp = matrix[cend][cend-c+cstart];
    			matrix[cend][cend-c+cstart] = prev;
    			prev = tmp;
    
    			// Third shift [cend][cend-c +cstart] go to [cend-cstart-c][r]
    			tmp = matrix[cend-c+cstart][r];
    			matrix[cend-c+cstart][r] = prev;
    			prev =tmp;
    
    			// Last shift
    			matrix[r][c] = prev;
    		}
    		cstart++;
    		cend--;
    	}
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.