4ms few lines C++ code Rotate Image 90 degree for O(1) space


  • 44
    S
    void rotate(vector<vector<int>>& matrix) {
            int n = matrix.size();
            int a = 0;
            int b = n-1;
            while(a<b){
                for(int i=0;i<(b-a);++i){
                    swap(matrix[a][a+i], matrix[a+i][b]);
                    swap(matrix[a][a+i], matrix[b][b-i]);
                    swap(matrix[a][a+i], matrix[b-i][a]);
                }
                ++a;
                --b;
            }
        }

  • 0

    This rotates it "ring by ring", right? Neat.


  • 6
    S

    Same idea, Java version, difficult to figure out the positions.
    1st for loop iterates rings to be rotated. 2nd one just changes elements' positions.

    public class Solution {
        public void rotate(int[][] matrix) {
            int n = matrix.length, temp;
    		for(int i = 0; i < n / 2; i++)
    			for(int j = i; j < n - i - 1; j++) {
    				temp = matrix[i][j];
    				matrix[i][j] = matrix[n - j - 1][i];
    				matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1];
    				matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1];
    				matrix[j][n - i - 1] = temp;
    			}
        }
    }

  • 0

    Really beautiful solution


  • 0
    J

    @SpicyDog Exactly the same idea.


Log in to reply
 

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