Simple Java solution


  • 0
    public class Solution {
        public void rotate(int[][] matrix) {
            if (matrix == null || matrix.length == 0) return;
            int n = matrix.length;
            for (int i = 0; i < n; i++) {
                for (int j = i + 1; j < n; j++) {
                    swap(matrix, i, j, j, i);
                }
            }
            for (int i = 0; i < n; i++) {
                int l = 0, r = n - 1;
                while (l < r)
                    swap(matrix, i, l++, i, r--);
            }
        }
        
        private void swap(int[][] matrix, int i1, int j1, int i2, int j2) {
            int tmp = matrix[i1][j1];
            matrix[i1][j1] = matrix[i2][j2]; 
            matrix[i2][j2] = tmp;
        }
    }
    

Log in to reply
 

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