Spiral Matrix

Spiral Matrix

 
We have given a matrix of m * n, we need to print the matrix in spiral fashion.



/**
* @author Gaurav Gupta
*/
public class SprialMatrix {
static void spiralPrint(int[][] matrix) {
int m = matrix.length;
if (m == 1 || m == 0)
return;
int n = matrix[0].length;
int row, col, dir, cycle;
row = col = dir = cycle = 0;
System.out.print(matrix[0][0] + " ");
for (int i = 1; i < (m * n); i++) {
switch (dir) {
case 0: {
if (col == n - cycle - 1) {
dir = 1;
row++;
} else {
col++;
}
break;
}
case 1: {
if (row == m - cycle - 1) {
dir = 2;
col--;
} else {
row++;
}
break;
}
case 2: {
if (col == cycle) {
row--;
dir = 3;
} else {
col--;
}
break;
}
case 3: {
if (row == cycle + 1) {
dir = 0;
col++;
cycle++;
} else {
row--;
}
}
}
System.out.print(matrix[row][col] + " ");
}
}
public static void main(String[] args) {
int[][] matrix = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } };
spiralPrint(matrix);
}
}


 






No Comments Yet

Leave a Reply

Your email address will not be published.

Lorem ipsum dolor sit amet, consectetur a dipiscing elit. Vivamus leo ante,

FOLLOW US ON