Minimum number of flips required such that a Binary Matrix doesn 't contain any path from the top left to the bottom right consisting only of 0s | The four direction coordinates changes from the current cell ; Function that returns true if there exists any path from the top - left to the bottom - right cell of 0 s ; If the bottom - right cell is reached ; Update the cell to 1 ; Traverse in all four directions ; Find the new coordinates ; If the new cell is valid ; Recursively call DFS ; If path exists , then return true ; Return false , if there doesn 't  exists any such path ; Function to flip the minimum number of cells such that there doesn 't exists any such path from (0, 0) to (N - 1, M - 1) cell consisting of 0s ; Case 1 : If no such path exists already ; Case 2 : If there exists only one path ; Case 3 : If there exists two - path ; Driver Code
let direction = [ [ - 1 , 0 ] , [ 0 , 1 ] , [ 0 , - 1 ] , [ 1 , 0 ] ] ; function dfs ( matrix , i , j , N , M ) { if ( i == N - 1 && j == M - 1 ) { return true ; } matrix [ i ] [ j ] = 1 ; for ( let k = 0 ; k < 4 ; k ++ ) { let newX = i + direction [ k ] [ 0 ] ; let newY = j + direction [ k ] [ 1 ] ; if ( newX >= 0 && newX < N && newY >= 0 && newY < M && matrix [ newX ] [ newY ] == 0 ) { if ( dfs ( matrix , newX , newY , N , M ) ) { return true ; } } } return false ; } function solve ( matrix ) { let N = matrix . length ; let M = matrix [ 0 ] . length ; if ( ! dfs ( matrix , 0 , 0 , N , M ) ) { return 0 ; } if ( ! dfs ( matrix , 0 , 0 , N , M ) ) { return 1 ; } return 2 ; } let mat = [ [ 0 , 1 , 0 , 0 ] , [ 0 , 1 , 0 , 0 ] , [ 0 , 0 , 0 , 0 ] ] ; document . write ( solve ( mat ) ) ;