Java: Spiral Traverse


 

Java: Spiral Traverse

This section explain the logic of spiral traverse of n*m matrix in java.

This section explain the logic of spiral traverse of n*m matrix in java.

Java: Spiral Traverse

This section explain the logic of spiral traverse of n*m matrix in java.

Spiral Traverse : Spiral Traverse means move in clock wise direction around a rectangular shape and finally print the middle one element.

It is a logical concept we are explaining it by example -

Example :

class SpiralTraverse {
	static int r = 4;
	static int c = 6;

	public static void main(String[] args) {
		int[][] a = { { 1, 2, 3, 4, 5, 6 }, { 7, 8, 9, 10, 11, 12 },
				{ 13, 14, 15, 16, 17, 18 }, { 19, 20, 21, 22, 23, 24 },

		};

		spiralPrint(r, c, a);
	}

	static void spiralPrint(int rIndex, int cIndex, int[][] a) {
		int i, k = 0, l = 0;
		rIndex--;
		cIndex--;
		/*
		 * k - starting row index rIndex - ending row index l - starting column index
		 * cIndex - ending column index i - iterator
		 */

		while (k <= rIndex && l <= cIndex) {
			/* Print the first row from the remaining rows */
			for (i = l; i <= cIndex; i++) {
				System.out.print(a[k][i] + " ");
			}
			k++;

			/* Print the last column from the remaining columns */
			for (i = k; i <= rIndex; i++) {
				System.out.print(a[i][cIndex] + " ");
			}
			cIndex--;

			/* Print the last row from the remaining rows */
			if (k <= rIndex) {

				for (i = cIndex; i >= l; i--) {
					System.out.print(a[rIndex][i] + " ");
				}
				rIndex--;
			}

			/* Print the first column from the remaining columns */
			if (l <= cIndex) {
				for (i = rIndex; i >= k; i--) {
					System.out.print(a[i][l] + " ");
				}
				l++;
			}
		}

	}
}

Description : In this example we are printing element of 4*6 matrix in spiral traversing. To traverse the each element put condition
while (k <= rIndex && l <= cIndex) .
Now we traverse first row of matrix and then the last column and then last row and then the first column and repeat the same till the while condition fails.

Output :

1 2 3 4 5 6 12 18 24 23 22 21 20 19 13 7 8 9 10 11 17 16 15 14 

Ads