Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Q1_07_Rotate_Matrix;
- import CtCILibrary.*;
- public class Question {
- public static int[][] rotateCW(int[][] mat) {
- int cols = mat.length;
- int rows = mat[0].length;
- int[][] newMatrix = new int[rows][cols];
- for (int r = 0; r < cols; r++) {
- for (int c = 0; c < rows; c++) {
- newMatrix[c][cols-1-r] = mat[r][c];
- }
- }
- return newMatrix;
- }
- public static int[][] rotate(int[][] mat, int flag) {
- int cols = mat.length;
- if (cols==0)
- return mat;
- int rows = mat[0].length;
- if (rows==0)
- return mat;
- int[][] newMatrix = new int[rows][cols];
- for (int r = 0; r < cols; r++) {
- for (int c = 0; c < rows; c++) {
- if (flag==0)
- newMatrix[rows-c-1][r] = mat[r][c];
- else
- newMatrix[c][cols-1-r] = mat[r][c];
- }
- }
- return newMatrix;
- }
- public static boolean rotate(int[][] matrix) {
- if (matrix.length == 0 || matrix.length != matrix[0].length) return false; // Not a square
- int n = matrix.length;
- for (int layer = 0; layer < n / 2; layer++) {
- int first = layer;
- int last = n - 1 - layer;
- for(int i = first; i < last; i++) {
- int offset = i - first;
- int top = matrix[first][i]; // save top
- // left -> top
- matrix[first][i] = matrix[last-offset][first];
- // bottom -> left
- matrix[last-offset][first] = matrix[last][last - offset];
- // right -> bottom
- matrix[last][last - offset] = matrix[i][last];
- // top -> right
- matrix[i][last] = top; // right <- saved top
- }
- }
- return true;
- }
- public static void main(String[] args) {
- int[][] matrix = AssortedMethods.randomMatrix(0, 0, 0, 9);
- AssortedMethods.printMatrix(matrix);
- matrix = rotate(matrix,0);
- System.out.println();
- AssortedMethods.printMatrix(matrix);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement