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