Popular Posts

Thursday, December 30, 2010

Spiral matrix

Given the size of input n,print a spiral matrix of size n*n
ex: n=3

9 2 3
8 1 4
7 6 5

By observing the above matrix,we can construct the matrix by building first left column after bottom column after right column after top column.
code looks like below:
// program to print spiral matrix
public static void getSpiralMatrix(int n) {
int count = n * n;
int[][] a = new int[n][n];
// we have to construct a spiral matrix of size n*n
for (int lower = 0, upper = n; lower <= upper; lower += 1, upper -= 1) {

// first we fill the left side of the column
for (int i = lower, j = lower; i < upper && count > 0; i++) {
a[i][j] = count--;
}

// fill the lower row
for (int i = upper - 1, j = lower + 1; j < upper - 1 && count > 0; j++) {
a[i][j] = count--;
}

// fill the right side of the column
for (int i = upper - 1, j = upper - 1; i >= lower && count > 0; i--) {
a[i][j] = count--;
}

// fill the upper row
for (int i = lower, j = upper - 2; j > lower && count > 0; j--) {
a[i][j] = count--;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}

Refer : http://www.geeksforgeeks.org/archives/10768

No comments:

Post a Comment