Given a matrix of ‘ O ’ and ‘ X ’ , replace ' O ' with ' X ' if surrounded by ' X ' | Size of given matrix is M X N ; A recursive function to replace previous value ' prevV ' at ' ( x , ▁ y ) ' and all surrounding values of ( x , y ) with new value ' newV ' . ; Base cases ; Replace the color at ( x , y ) ; Recur for north , east , south and west ; Returns size of maximum size subsquare matrix surrounded by ' X ' ; Step 1 : Replace all ' O ' with ' - ' ; Call floodFill for all ' - ' lying on edges Left side ; Right side ; Top side ; Bottom side ; Step 3 : Replace all ' - ' with ' X ' ; Driver Code
let M = 6 ; let N = 6 ; function floodFillUtil ( mat , x , y , prevV , newV ) { if ( x < 0 x >= M y < 0 y >= N ) return ; if ( mat [ x ] [ y ] != prevV ) return ; mat [ x ] [ y ] = newV ; floodFillUtil ( mat , x + 1 , y , prevV , newV ) ; floodFillUtil ( mat , x - 1 , y , prevV , newV ) ; floodFillUtil ( mat , x , y + 1 , prevV , newV ) ; floodFillUtil ( mat , x , y - 1 , prevV , newV ) ; } function replaceSurrounded ( mat ) { for ( let i = 0 ; i < M ; i ++ ) for ( let j = 0 ; j < N ; j ++ ) if ( mat [ i ] [ j ] == ' ' ) mat [ i ] [ j ] = ' ' ; for ( let i = 0 ; i < M ; i ++ ) if ( mat [ i ] [ 0 ] == ' ' ) floodFillUtil ( mat , i , 0 , ' ' , ' ' ) ; for ( let i = 0 ; i < M ; i ++ ) if ( mat [ i ] [ N - 1 ] == ' ' ) floodFillUtil ( mat , i , N - 1 , ' ' , ' ' ) ; for ( let i = 0 ; i < N ; i ++ ) if ( mat [ 0 ] [ i ] == ' ' ) floodFillUtil ( mat , 0 , i , ' ' , ' ' ) ; for ( let i = 0 ; i < N ; i ++ ) if ( mat [ M - 1 ] [ i ] == ' ' ) floodFillUtil ( mat , M - 1 , i , ' ' , ' ' ) ; for ( let i = 0 ; i < M ; i ++ ) for ( let j = 0 ; j < N ; j ++ ) if ( mat [ i ] [ j ] == ' ' ) mat [ i ] [ j ] = ' ' ; } let mat = [ [ ' ' , ' ' , ' ' , ' ' , ' ' , ' ' ] , [ ' ' , ' ' , ' ' , ' ' , ' ' , ' ' ] , [ ' ' , ' ' , ' ' , ' ' , ' ' , ' ' ] , [ ' ' , ' ' , ' ' , ' ' , ' ' , ' ' ] , [ ' ' , ' ' , ' ' , ' ' , ' ' , ' ' ] , [ ' ' , ' ' , ' ' , ' ' , ' ' , ' ' ] ] ; replaceSurrounded ( mat ) ; for ( let i = 0 ; i < M ; i ++ ) { for ( let j = 0 ; j < N ; j ++ ) document . write ( mat [ i ] [ j ] + " " ) ; document . write ( " " ) ; }