Advertisement
Guest User

Untitled

a guest
Mar 27th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. package Q1_07_Rotate_Matrix;
  2.  
  3. import CtCILibrary.*;
  4.  
  5. public class Question {
  6.  
  7. public static int[][] rotateCW(int[][] mat) {
  8.  
  9. int cols = mat.length;
  10. int rows = mat[0].length;
  11.  
  12. int[][] newMatrix = new int[rows][cols];
  13.  
  14. for (int r = 0; r < cols; r++) {
  15. for (int c = 0; c < rows; c++) {
  16. newMatrix[c][cols-1-r] = mat[r][c];
  17. }
  18. }
  19.  
  20. return newMatrix;
  21. }
  22.  
  23. public static int[][] rotate(int[][] mat, int flag) {
  24.  
  25. int cols = mat.length;
  26.  
  27. if (cols==0)
  28. return mat;
  29.  
  30. int rows = mat[0].length;
  31.  
  32. if (rows==0)
  33. return mat;
  34.  
  35. int[][] newMatrix = new int[rows][cols];
  36.  
  37. for (int r = 0; r < cols; r++) {
  38. for (int c = 0; c < rows; c++) {
  39. if (flag==0)
  40. newMatrix[rows-c-1][r] = mat[r][c];
  41. else
  42. newMatrix[c][cols-1-r] = mat[r][c];
  43. }
  44. }
  45.  
  46. return newMatrix;
  47. }
  48.  
  49. public static boolean rotate(int[][] matrix) {
  50. if (matrix.length == 0 || matrix.length != matrix[0].length) return false; // Not a square
  51. int n = matrix.length;
  52.  
  53. for (int layer = 0; layer < n / 2; layer++) {
  54. int first = layer;
  55. int last = n - 1 - layer;
  56. for(int i = first; i < last; i++) {
  57. int offset = i - first;
  58. int top = matrix[first][i]; // save top
  59.  
  60. // left -> top
  61. matrix[first][i] = matrix[last-offset][first];
  62.  
  63. // bottom -> left
  64. matrix[last-offset][first] = matrix[last][last - offset];
  65.  
  66. // right -> bottom
  67. matrix[last][last - offset] = matrix[i][last];
  68.  
  69. // top -> right
  70. matrix[i][last] = top; // right <- saved top
  71. }
  72. }
  73. return true;
  74. }
  75.  
  76. public static void main(String[] args) {
  77. int[][] matrix = AssortedMethods.randomMatrix(0, 0, 0, 9);
  78. AssortedMethods.printMatrix(matrix);
  79. matrix = rotate(matrix,0);
  80. System.out.println();
  81. AssortedMethods.printMatrix(matrix);
  82. }
  83.  
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement