Print n x n spiral matrix using O ( 1 ) extra space | Prints spiral matrix of size n x n containing numbers from 1 to n x n ; x stores the layer in which ( i , j ) th element lies ; Finds minimum of four inputs ; For upper right half ; For lower left half ; Driver code ; Print a n x n spiral matrix in O ( 1 ) space
function printSpiral ( n ) { for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 0 ; j < n ; j ++ ) { let x ; x = Math . min ( Math . min ( i , j ) , Math . min ( n - 1 - i , n - 1 - j ) ) ; if ( i <= j ) document . write ( ` ${ ( n - 2 * x ) * ( n - 2 * x ) - ( i - x ) - ( j - x ) } ` ) ; else document . write ( ` ${ ( n - 2 * x - 2 ) * ( n - 2 * x - 2 ) + ( i - x ) + ( j - x ) } ` ) ; } document . write ( " " ) ; } } let n = 5 ; printSpiral ( n ) ;