题目
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
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.
分析
旋转操作很简单,找到规律就可以啦。
别的。。。突然发现题目中不让申请其他数组空间。而我的思路是dfs。就是利用dfs进行遍历,申请了marked数组来标记已经旋转过的位置,应该是不对的。
另外就是用数学方法计算到底怎样才能不多旋转,也非常简单。按框框来算,每一个框框只需要旋转(n-1)*4次就可以啦
class Solution {
public static void rotate(int[][] xx) {
int n = xx.length;
boolean[][] marked = new boolean[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (marked[i][j] == true) {
continue;
}
int newValue = xx[i][j];
dfs(xx, j, n -1 - i, newValue, marked);
}
} }
public static void dfs(int[][] xx, int x, int y, int value, boolean[][] marked) {
int newValue = xx[x][y];
xx[x][y] = value;
marked[x][y] = true;
if (!marked[y][xx.length - 1-x]) {
dfs(xx, y, xx.length - x-1, newValue, marked);
}
}
}