Advertisement
Guest User

Untitled

a guest
Apr 24th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. package com.anirudh.matrix;
  2.  
  3. /**
  4. * Created by paanir on 4/24/17.
  5. */
  6. /*
  7. 48. Rotate Image
  8. You are given an n x n 2D matrix representing an image.
  9.  
  10. Rotate the image by 90 degrees (clockwise).
  11.  
  12. Follow up:
  13. Could you do this in-place?
  14. */
  15. public class RotateImage {
  16.  
  17.  
  18. //O(1) space; O(n^2) time
  19. int[][] matrix;
  20.  
  21. public void rotateCW(int up, int down, int left, int right){
  22. if(up > down || left > right)
  23. return;
  24.  
  25. int d = down;
  26. int l = left;
  27. int r = right;
  28. int u = up;
  29.  
  30. while(l < right){ //for all except the last element
  31. int temp = matrix[up][l];
  32. matrix[up][l] = matrix[d][left];
  33. matrix[d][left] = matrix[down][r];
  34. matrix[down][r] = matrix[u][right];
  35. matrix[u][right] = temp;
  36. --d;
  37. --r;
  38. ++u;
  39. ++l;
  40. }
  41. rotateCW(up+1, down-1, left + 1, right - 1); //get into inner matrix
  42. }
  43. public void rotate(int[][] matrix) {
  44. this.matrix = matrix;
  45. rotateCW(0, matrix.length - 1, 0, matrix[0].length - 1);
  46. }
  47.  
  48. //----------------------------------------------
  49. //O(n^2) space; O(n^2) time
  50. public void rotateNaive(int[][] matrix) {
  51. int numRows = matrix.length;
  52. int numCols = matrix[0].length;
  53. int [][] newMatrix = new int[numCols][numRows];
  54. int nR = 0;
  55. int nC = numCols - 1;
  56. //make new matrix
  57. for(int r = 0; r < numRows; ++r){
  58. for(int c = 0; c < numCols; ++c){
  59. newMatrix[nR][nC] = matrix[r][c];
  60. ++nR;
  61. }
  62. nR = 0;
  63. --nC;
  64. }
  65. //copy to old matrix
  66. for(int r = 0; r < numRows; ++r){
  67. for(int c = 0; c < numCols; ++c){
  68. matrix[r][c] = newMatrix[r][c];
  69. }
  70. }
  71. }
  72.  
  73.  
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement