Using transpose and flip operations


  • 0
    K
    public class Solution {
        public void transpose(int [][]matrix,int n) {
            for(int i=0; i<n; i++) {
                for(int j=0; j<n; j++) {
                    if(i+j < n-1) { // flip only left diagonal cells
                        int temp = matrix[i][j];
                        matrix[i][j] = matrix[n-j-1][n-i-1];
                        matrix[n-j-1][n-i-1] = temp;
                    }
                }
            }
        }
        
        public void flipVertically(int [][] matrix, int n) {
            for(int i=0; i<(n+1)/2; i++) {
                for(int j=0; j<n; j++) {
                    int temp = matrix[i][j];
                    matrix[i][j] = matrix[n-i-1][j];
                    matrix[n-i-1][j] = temp;
                }
            }
        }
        
        public void rotate(int[][] matrix) {
            int n = matrix.length;
            transpose(matrix, n);
            flipVertically(matrix, n);
        }
    }

Log in to reply
 

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