Given a matrix and a flag, if flag = 1, rotate the matrix by 90 degrees clockwise. If flag = 0, rotate the matrix by 90 degrees counterclockwise.
/*
First transpose the matrix and then rotate it.
time:O(m*n), space:O(1)
*/
import java.util.*;
public class Solution {
public static int[][] rotateMatrix(int[][] matrix, int flag) {
if (matrix == null || matrix.length == 0 ||
matrix[0] == null || matrix[0].length == 0) {
return matrix;
}
if (flag != 0 && flag != 1) {
return matrix;
}
int[][] res = transpose(matrix);
return rotate(res, flag);
}
public static int[][] transpose(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int[][] res = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
res[i][j] = matrix[j][i];
}
}
return res;
}
public static int[][] rotate(int[][] matrix, int flag) {
int m = matrix.length;
int n = matrix[0].length;
if (flag == 1) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n / 2; j++) {
swap(matrix, i, j, i , n - 1 - j);
}
}
} else {
for (int i = 0; i < m / 2; i++) {
for (int j = 0; j < n; j++) {
swap(matrix, i, j, m - 1- i, j);
}
}
}
return matrix;
}
public static void swap(int[][] matrix, int a, int b,
int c, int d) {
int tmp = matrix[a][b];
matrix[a][b] = matrix[c][d];
matrix[c][d] = tmp;
}
public static void main(String[] args) {
int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
int[][] res = rotateMatrix(matrix, 0);
for (int i = 0; i < res.length; i++) {
for (int j = 0; j < res[0].length; j++) {
System.out.print(res[i][j]+" ");
}
System.out.println(" ");
}
}
}
No comments:
Post a Comment