Circular Matrix ( Construct a matrix with numbers 1 to m * n in spiral way ) | Javascript program to fill a matrix with values from 1 to n * n in spiral fashion . ; Fills a [ m ] [ n ] with values from 1 to m * n in spiral fashion . ; Initialize value to be filled in matrix ; k - starting row index m - ending row index l - starting column index n - ending column index ; Print the first row from the remaining rows ; Print the last column from the remaining columns ; Print the last row from the remaining rows ; Print the first column from the remaining columns ; Driver program to test above functions
const MAX = 100 ; function spiralFill ( m , n , a ) { let val = 1 ; let k = 0 , l = 0 ; while ( k < m && l < n ) { for ( let i = l ; i < n ; ++ i ) a [ k ] [ i ] = val ++ ; k ++ ; for ( let i = k ; i < m ; ++ i ) a [ i ] [ n - 1 ] = val ++ ; n -- ; if ( k < m ) { for ( let i = n - 1 ; i >= l ; -- i ) a [ m - 1 ] [ i ] = val ++ ; m -- ; } if ( l < n ) { for ( let i = m - 1 ; i >= k ; -- i ) a [ i ] [ l ] = val ++ ; l ++ ; } } } let m = 4 , n = 4 ; let a = Array . from ( Array ( MAX ) , ( ) => new Array ( MAX ) ) ; spiralFill ( m , n , a ) ; for ( let i = 0 ; i < m ; i ++ ) { for ( let j = 0 ; j < n ; j ++ ) document . write ( a [ i ] [ j ] + " " ) ; document . write ( " " ) ; }