Advertisement
Guest User

Untitled

a guest
Feb 18th, 2020
324
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.43 KB | None | 0 0
  1. /* Input: 2D Array
  2.  * 1 2 3
  3.  * 4 5 6
  4.  * 7 8 9
  5.  *
  6.  * Output: 1 2 3 5 9 8 7 4 5
  7.  */
  8.  
  9. public void spiral(int[][] mat)
  10. {
  11.     int[][] rcSigns = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // The Direction Change Pattern Of The Spiral
  12.     StringBuilder indices = new StringBuilder(); // Stores All Indexes Printed To The Screen (With A Space Between Each Index)
  13.     int numCount = 0; // Number Of Indices In The "indices" variable
  14.  
  15.     int rPat = 0, cPat = 0; // Current Spiral Sign/Pattern
  16.     int rSign = rcSigns[0][0], cSign = rcSigns[0][1]
  17.     int r = 0, c = 0; // Row Index | Column Index
  18.     int nums = mat.length * mat[0].length; // Number of Elements In The 2D Matrix
  19.  
  20.     while(numCount < nums)
  21.     {
  22.         String index = r + "" + c;
  23.         indices.append(index);
  24.         numCount++;
  25.         System.out.println(mat[r][c]);
  26.  
  27.         r += rSign;
  28.         c += cSign;
  29.  
  30.         if(r == 0 && c == mat[r].length - 1 ||
  31.            r == mat.length - 1 && c == mat[r].length - 1 ||
  32.            r == mat.length - 1 && c == 0 ||
  33.            indices.contain(index))
  34.         {
  35.             // Go Back One Index
  36.             r -= rSign;
  37.             c -= cSign;
  38.            
  39.             // Change The Direction of the Spiral Pattern
  40.             // I Use (Mod 4) Because There Are 4 Possible Patterns And When I Am At Index 3 And Increment By One, I Want To Go Back To
  41.             // Index 0, And Restart The Spiral Direction Patterns
  42.             rSign = rcSigns[++rPat % 4][0];
  43.             cSign = rcSigns[++cPat % 4][1];
  44.            
  45.             // Increment In New Spiral Direction
  46.             r += rSign;
  47.             c += cSign;
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement