RotateImage
Suddenly I found some tricks with matrix rotate.
There are two basic operations: transpose() and swapRows().
transpose(): swap matrix[i][j] with matrix[j][i]
swapRows(): swap the first row with the last row and keep swapping until we reach middle;
Rotate Left(counter-clockwise):
- transpose()
- swapRows()
Rotate Right(clockwise):
- swapRows()
- transpose()
public class RotateImage {
public static void main(String[] args) {
int[][] matrix = {{1,2,3}, {4,5,6}, {7,8,9}};
int[][] ans = null;
System.out.println("original");
print(matrix);
System.out.println("right");
ans = rotateImage(matrix, 1);
print(ans);
}
public static void print(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
public static int[][] rotateImage(int[][] matrix, int flag) {
if (flag == 0) {
transpose(matrix);
swapRows(matrix);
} else {
swapRows(matrix);
transpose(matrix);
}
return matrix;
}
public static void swapRows(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
return;
}
int m = matrix.length, start = 0, end = m - 1;
while (start < end) {
int[] tmp = matrix[start];
matrix[start] = matrix[end];
matrix[end] = tmp;
start++;
end--;
}
}
public static void transpose(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
return;
}
int m = matrix.length, n = matrix[0].length;
for (int i = 0; i < m; i++) {
for (int j = i + 1; j < n; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
}
}