Concise Java solution using only swaps


  • 0
    J
    public class Solution {
    public void rotate(int[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return;
        }
    
        final int N = matrix.length;
    
        for(int i = 0; i <= N / 2; i++) {
            for(int j = i; j < N - i - 1; j++) {
                swap(matrix, i, j, j, N - i - 1);
    
                swap(matrix, i, j, N - i - 1, N - j - 1);
    
                swap(matrix, i, j, N - j - 1, i);
            }
        }
    }
    
    private void swap(int[][] matrix, int si, int sj, int di, int dj) {
        int tmp = matrix[si][sj];
    
        matrix[si][sj] = matrix[di][dj];
        matrix[di][dj] = tmp;
    }
    }

Log in to reply
 

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