A utility function to print grid
function print ( grid ) { for ( let i = 0 ; i < N ; i ++ ) { for ( let j = 0 ; j < N ; j ++ ) document . write ( grid [ i ] [ j ] + " " ) ; document . write ( " " ) ; } }