You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
Could you do this in-place?
public class Solution { private void swap(int[][] matrix, int i, int j, int x, int y){ // Error: A very silly mistake i != j || x != y if(i != x || j != y){ // Error: Again, we have to judge identity if using bitwise method. matrix[i][j] = matrix[i][j] ^ matrix[x][y]; matrix[x][y] = matrix[i][j] ^ matrix[x][y]; matrix[i][j] = matrix[i][j] ^ matrix[x][y]; } } public void rotate(int[][] matrix) { int n = matrix.length; if(0 == n) return; for(int i = 0; i < (n+1)/2; ++i) // Error: Notice for n is odd, the rotation is not a square. for(int j = 0; j < n/2; ++j){ int si = j; int sj = n -1 -i; swap(matrix, i, j, si, sj); si = n - 1 - i; sj = n - 1 - j; swap(matrix, i, j, si, sj); si = n - 1 - j; sj = i; swap(matrix, i, j, si, sj); } return; } }
No comments:
Post a Comment