| 2 | { |
| 3 | //Function to return a list of integers denoting spiral traversal of matrix. |
| 4 | static ArrayList<Integer> spirallyTraverse(int matrix[][], int r, int c) |
| 5 | { |
| 6 | // Declaraing an arrayList for storing the results |
| 7 | ArrayList<Integer> spiralMat = new ArrayList<Integer>(); |
| 8 | // Declaring 4 pointers |
| 9 | int startRow=0; |
| 10 | int endRow=r-1; |
| 11 | int startColumn=0; |
| 12 | int endColumn=c-1; |
| 13 | |
| 14 | // Logic goes here |
| 15 | |
| 16 | while(startRow<=endRow && startColumn<=endColumn) |
| 17 | { |
| 18 | //from the starting row |
| 19 | for(int i=startColumn;i<=endColumn;i++) |
| 20 | { |
| 21 | spiralMat.add(matrix[startRow][i]); |
| 22 | } |
| 23 | startRow++; |
| 24 | |
| 25 | //from the ending column |
| 26 | for(int i=startRow;i<=endRow;i++) |
| 27 | { |
| 28 | spiralMat.add(matrix[i][endColumn]); |
| 29 | } |
| 30 | endColumn--; |
| 31 | |
| 32 | if(startRow<=endRow) |
| 33 | { |
| 34 | //from the ending row |
| 35 | for(int i=endColumn;i>=startColumn;i--) |
| 36 | { |
| 37 | spiralMat.add(matrix[endRow][i]); |
| 38 | } |
| 39 | endRow--; |
| 40 | } |
| 41 | |
| 42 | if(startColumn<=endColumn) |
| 43 | { |
| 44 | //from the starting Column |
| 45 | for(int i=endRow;i>=startRow;i--) |
| 46 | { |
| 47 | spiralMat.add(matrix[i][startColumn]); |
| 48 | } |
| 49 | startColumn++; |
| 50 | } |
| 51 | } |
| 52 | return spiralMat; |
| 53 | } |
| 54 | } |