You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
class Solution { public void rotate(int[][] matrix) { int m = matrix.length, n = matrix[0].length; int[][] visited = new int[m][n]; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(visited[i][j] == 1) continue; int x = i, y = j; int value = matrix[i][j]; while(true){ int s = n-1-x, t = y; if(visited[t][s] == 1) break; int temp = matrix[t][s]; matrix[t][s] = value; value = temp; visited[t][s] = 1; x = t; y = s; } } } } }
Solution 2
此方法类似Solution 1,但是并非原地算法。
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { publicvoidrotate(int[][] matrix) { intm= matrix.length, n = matrix[0].length; int[][] mat = newint[m][n]; for(inti=0; i < m; i++){ for(intj=0; j < n; j++){ ints= n-1-i, t = j; mat[t][s] = matrix[i][j]; } } for(inti=0; i < m; i++){ for(intj=0; j < n; j++){ matrix[i][j] = mat[i][j]; } } } }