A new idea of this question


  • 1
    L

    I treat the matrix as a circle, every loop to move the circle clockwise which need to change 4 values.

    here is my solution:

    public class Solution {
        public void rotate(int[][] matrix) {
            if (matrix == null) {
                return;
            }
    
            int len = matrix.length;
            for (int i = len / 2 + len % 2 - 1; i >= 0; i--) {
                rotateCycle(matrix, i);
            }
        }
    
        private void rotateCycle(int[][] matrix, int circle) {
            int len = matrix.length;
            int pos1x = circle;
            int pos1y = circle;
            int pos2x = circle;
            int pos2y = len - 1 - circle;
            int pos3x = len - 1 - circle;
            int pos3y = len - 1 - circle;
            int pos4x = len - 1 - circle;
            int pos4y = circle;
            for (int i = 0; i <= len - 2 - (circle * 2); i++) {
                int temp = matrix[pos4x][pos4y];
                matrix[pos4x][pos4y] = matrix[pos3x][pos3y];
                matrix[pos3x][pos3y] = matrix[pos2x][pos2y];
                matrix[pos2x][pos2y] = matrix[pos1x][pos1y];
                matrix[pos1x][pos1y] = temp;
                pos1y += 1;
                pos2x += 1;
                pos3y -= 1;
                pos4x -= 1;
            }
        }
    }
    

  • 0
    J

    @loveinliuy
    Nice - I believe we have the same idea. Here's a slightly different way:

    public class Solution {
        public void Rotate(int[,] matrix) {
            
    		int len = matrix.GetLength(0);
            for(int i = 0; i < len; i++)
            {
                for(int j = i; j < len-i-1 ; j++) //only need to shift the top middle triangle; i.e., the stars in this pic since we're moving all four places at once.
    //				* * * x
    //				x * x x
    //				x x x x
    //				x x x x 
                {
    		//RULE: (i, j) => (j, len-1-i); easiest to trace the rule up from the bottom of the code.
    		//IDEA: copy top to tmp. move left to top, move bot to left, move right to bot. move tmp to r.
                    var t = matrix[i, j];
    		matrix[i, j] = matrix[len-1-j, i];
                    matrix[len-1-j, i] = matrix[len-1-i, len-1-j ];
                    matrix[len-1-i, len-1-j ] = matrix[j, len-1-i];
    		matrix[j, len-1-i] = t; 
    	    }
            }
        }
    }
    

Log in to reply
 

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