網址
題目
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.
Example 1:
Given input matrix = [ [1,2,3], [4,5,6], [7,8,9] ],
rotate the input matrix in-place such that it becomes: [ [7,4,1], [8,5,2], [9,6,3] ]
解法
辣雞韓梅梅,做了好久,這本該很快做出來的,思路就是把整個正方形分成一圈一圈的框,將框中每一個值旋轉90操作,細節還是有點的。。總是對index不是很敏感,需要通過debug來調對。這次沒看別人的解法還挺棒的,再接再厲!
class Solution {
int[][] dir = {{0,1},{1,0},{0,-1},{-1,0}};
public void rotate(int[][] matrix) {
for(int i=0; i<matrix.length/2; i++){
matrix = rotate_one_square(matrix, i, matrix.length-i-1);
}
}
private int[][] rotate_one_square(int[][] matrix, int begin, int end){
System.out.println("beg "+begin+" "+end);
int len = end - begin + 1;
int next_column, next_row, cur_row, cur_column, cur_value;
int[] arr = new int[len-1];
cur_row = begin;
cur_column = begin;
for(int i = 0; i < len-1; i++){
arr[i] = matrix[cur_row][cur_column+i];
}
System.out.println("cur "+cur_row+" "+cur_column);
for(int j = 0; j < 4; j++){
next_row = cur_row + dir[j][0]*(len-1);
next_column = cur_column + dir[j][1]*(len-1);
System.out.println("before next "+next_row+" "+next_column);
if (next_row >= begin+len){
next_column += next_row - begin - len + 1;
next_row = begin + len - 1;
}
if (next_column >= begin+len){
next_row += next_column - begin - len + 1;
next_column = begin + len - 1;
}
System.out.println("next "+next_row+" "+next_column);
for(int i = 0; i < len-1; i++){
System.out.println("replace "+(next_row+i*dir[(j+1)%4][0])+" "+(next_column+i*dir[(j+1)%4][1])+" with "+ arr[i]);
int temp = matrix[next_row+i*dir[(j+1)%4][0]][next_column+i*dir[(j+1)%4][1]];
matrix[next_row+i*dir[(j+1)%4][0]][next_column+i*dir[(j+1)%4][1]] = arr[i];
arr[i] = temp;
}
cur_row = next_row;
cur_column = next_column;
}
return matrix;
}
}