Reputation: 1
This is the code:
public class spiral {
public static void main(String[] args) {
int n = 5;
generateSpiralMat(n);
}
static void generateSpiralMat(int n) {
int[][] mat = new int[n][n] ;
int topRow =0, rightCol = n-1, bottonRow = n-1, leftCol = 0 ;
int num = 1 ;
while( num < n*n + 1 ) {
//topRow -> leftCol to rightCol
for(int i=leftCol; i<rightCol; i++) {
mat[topRow][i] = num;
num ++ ;
}
//rightCol -> topRow to bottomRow
for(int j =topRow; j<bottonRow; j++){
mat[j][rightCol] = num ;
num++ ;
}
//bottomRow -> rightCol to leftCol
for(int i=rightCol; i> leftCol; i--) {
mat[bottonRow][i] = num;
num++ ;
}
//leftCol -> bottomRow to topRow
for(int j=bottonRow; j>topRow; j--) {
mat[j][leftCol] = num ;
num ++ ;
}
topRow += 1 ;
bottonRow -= 1 ;
leftCol += 1 ;
rightCol -= 1 ;
}
printMat(mat);
}
static void printMat(int[][] mat) {
for(int i=0; i< mat.length; i++) {
for(int j=0; j< mat[i].length; j++) {
System.out.print( mat[i][j] + " ");
}
System.out.println();
}
}
}
Even length matrix working well but code is showing error in runtime only for odd length matrix
I was expecting that the code would generate a spiral matrix as per the given question.
Upvotes: 0
Views: 48
Reputation: 395
void spiral( int side ) {
int matriz[][] = new int[ side ][ side ];
int length = side * side;
int count = 0;
int top = side - 1;
int floor = 0;
int sector = 0;
int j = 0, k = 0;
for( int i = 0; i < length; i++ ) {
matriz[ j ][ k ] = count;
switch( sector ) {
case 3: j--;
if( j == floor ) {
sector = 0;
top -= 1;
}
break;
case 2: k--;
if( k == floor ) {
floor++;
sector++;
}
break;
case 1: j++;
if( j == top ) {
sector++;
}
break;
case 0: k++;
if( k == top ) {
sector++;
}
break;
}
count++;
}
}
We divide the operation into four stages:
A) advance in the columns
B) advance in the rows
C) back in the columns
D) back in rows
when it reaches the corresponding limit, it goes to the next sector, in sector "3" the upper limit is modified, and in "2" the lower limit.
Upvotes: 1