3 ways in Java to solve the problem


  • 0

    The first idea come to my mind is quite straight: divide the original matrix into four parts then use a temp to exchange between them

        public void rotate(int[][] matrix) {
            int len = matrix.length;
            for (int i = 0; i < (len + 1) / 2; i++) {
                for (int j = 0; j < len / 2; j++) {
                    int temp = 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] = temp;
                }
            }
        }
    

    after reviewing others' solutions, there are two more idea

    1. this one divide matrix into triangle parts
      which is from @baifriend https://discuss.leetcode.com/topic/20212/clear-java-solution
    public void rotate(int[][] matrix) {
        int n=matrix.length;
        for (int i=0; i<n/2; i++) 
            for (int j=i; j<n-i-1; j++) {
                int tmp=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]=tmp;
            }
        }
    
    1. use matrix reverse and swap to help
      which is from @shichaotan https://discuss.leetcode.com/topic/6796/a-common-method-to-rotate-the-image
        public void rotate(int[][] matrix) {
            int len = matrix.length;
            for (int i = 0; i < len; i++) {
                for (int j = i + 1; j < len; j++) {
                    swap(matrix, i, j, j, i);
                }
            }
            for (int i = 0; i < len; i++) {
                for (int j = 0; j < len / 2; j++) {
                    swap(matrix, i, j, i, len - 1 - j);
                }
            }
        }
        
        public void swap(int[][] matrix, int i, int j, int a, int b) {
            int temp = matrix[i][j];
            matrix[i][j] = matrix[a][b];
            matrix[a][b] = temp;
        }
    

Log in to reply
 

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