Wednesday, April 2, 2014

Rotate Image @LeetCode

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?
package leetcode;
/**
* Solution: analysis and calculate coordinate.
* 1. swap lines by mid line
* 2. swap element by diagonal
* Don't extract swap function, this is not C/C++!
*
* in-place is really head to understand.
* Reference: http://discuss.leetcode.com/questions/226/rotate-image
*
* @author jeffwan
* @date Apr 2, 2014
*/
public class RotateImage {
// in-place way
public void rotate(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return;
}
int n = matrix.length;
for (int i = 0; i < n / 2; i++) {
for (int j = 0; j < (n + 1) / 2; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[n - j - 1][i];
matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1];
matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1];
matrix[j][n - i - 1] = temp;
}
}
}
public void rotate1(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return;
}
int n = matrix.length;
// turn over along mid line
for (int i = 0; i < n / 2; i++) {
for (int j = 0; j < n; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[n - i - 1][j];
matrix[n - i - 1][j] = temp;
}
}
// swap along diagonal, only traversal half matrix.
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
/*
* Always think brute force way first!
* Copy to a new matrix, and assign to the original one.
*/
public void rotate2(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return;
}
int n = matrix.length;
int[][] newMatrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
newMatrix[i][j] = matrix[n - 1 - j][i];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = newMatrix[i][j];
}
}
}
}

No comments:

Post a Comment