48. Rotate Image

/**
48. Rotate Image
https://leetcode.com/problems/rotate-image/description/
*/
class Solution {
    public void rotate(int[][] matrix) {
        //N x N matrix have floor(N/2) square cycers, for example 4x4 matrix have 2 cycles
        if (matrix==null || matrix[0].length==0){
            return;
        }
        int n = matrix.length;
        for (int x = 0;x<n/2;x++){
            for (int y = x;y<n-x-1;y++){
                int temp = matrix[x][y];
                //move value from right to top
                matrix[x][y] = matrix[n-1-y][x];
                // move values from bottom to right 
                 matrix[n-1-y][x]= matrix[n-1-x][n-1-y];
                  // move values from left to bottom 
                matrix[n-1-x][n-1-y] = matrix[y][n-1-x];
                //assign temp to left
                matrix[y][n-1-x] = temp;
            }
        }
    }
}

//kotlin


class Solution {
fun rotate(matrix: Array<IntArray>): Unit {
if (matrix.isEmpty() || matrix[0].isEmpty())
return
val n = matrix.size
for (i in 0..(n / 2 - 1)) {
for (j in i..n - 2 - i) {
val temp = matrix[i][j]
println("temp:" + temp)
println("matrix[n-1-j][i]:" + matrix[n - 1 - j][i])
matrix[i][j] = matrix[n - 1 - j][i]
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j]
matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i]
matrix[j][n - 1 - i] = temp
}
}
}
}
 
原文地址:https://www.cnblogs.com/johnnyzhao/p/11483977.html