|
| 1 | +package matrix; |
| 2 | +import java.io.*; |
| 3 | + |
| 4 | +/* |
| 5 | + * Spiral traversal on a Matrix |
| 6 | + */ |
| 7 | + |
| 8 | +/* |
| 9 | + * GIven an 2D array, print it in spiral form. |
| 10 | + * See the following examples. |
| 11 | + * |
| 12 | + * Inputs: |
| 13 | + * 01 02 03 04 |
| 14 | + * 05 06 07 08 |
| 15 | + * 09 10 11 12 |
| 16 | + * 13 14 15 16 |
| 17 | + * |
| 18 | + * Output: |
| 19 | + * 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 |
| 20 | + * |
| 21 | + * Explanation: |
| 22 | + * The output is matrix in spiral format. |
| 23 | + */ |
| 24 | + |
| 25 | +/* Graphical Try: |
| 26 | + * |
| 27 | + * 01-- 02-- 03-- 04 |
| 28 | + * | |
| 29 | + * 05-- 06-- 07 08 |
| 30 | + * | | | |
| 31 | + * 09 10 11 12 |
| 32 | + * | | |
| 33 | + * 13-- 14-- 15 --16 |
| 34 | + * |
| 35 | + * Output: |
| 36 | + * 1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10 |
| 37 | + */ |
| 38 | + |
| 39 | +@SuppressWarnings("unused") |
| 40 | +public class Matrix_Problem_01 { |
| 41 | + |
| 42 | + static void spiralPrint(int m, int n, int[][] a) { |
| 43 | + |
| 44 | + System.out.println("Spiral Traversal of given matrix is: "); |
| 45 | + int i, k = 0, l = 0; |
| 46 | + |
| 47 | + /* |
| 48 | + * k - starting row index |
| 49 | + * m - ending row index |
| 50 | + * l - starting column index |
| 51 | + * n - ending column index |
| 52 | + * i - iterator |
| 53 | + */ |
| 54 | + |
| 55 | + while(k < m && l < n) { |
| 56 | + |
| 57 | + |
| 58 | + for( i = l ; i < n ; ++i) |
| 59 | + System.out.print(a[k][i] + " "); |
| 60 | + k++; |
| 61 | + |
| 62 | + for(i = k ; i < m ; ++i) |
| 63 | + System.out.print(a[i][n - 1] + " "); |
| 64 | + n--; |
| 65 | + |
| 66 | + if(l < n) { |
| 67 | + for(i = m - 1 ; i >= k ; --i) |
| 68 | + System.out.print(a[i][l] + " "); |
| 69 | + l++; |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + } |
| 74 | + |
| 75 | + public static void main(String[] args) { |
| 76 | + |
| 77 | + int R = 3; |
| 78 | + int C = 6; |
| 79 | + int a[][] = { { 1 , 2 , 3 , 4 , 5 , 6 }, |
| 80 | + { 7 , 8 , 9 , 10 , 11 , 12 }, |
| 81 | + { 13 , 14 , 15 , 16 , 17 , 18 } |
| 82 | + }; |
| 83 | + |
| 84 | + spiralPrint(R,C,a); |
| 85 | + } |
| 86 | + |
| 87 | +} |
0 commit comments