Check if a path exists for a cell valued 1 to reach the bottom right corner of a Matrix before any cell valued 2 | Function to check if cell with value 1 doesn 't reaches the bottom right cell or not ; Number of rows and columns ; Initialise the deque ; Traverse the matrix ; Push 1 to front of queue ; Push 2 to back of queue ; Store all the possible direction of the current cell ; Run multi - source BFS ; Get the front element ; Pop the front element ; If 1 reached corner first ; Insert new point in queue ; If 1 can 't reach the bottom  right then return false ; Given matrix ; Function Call
function reachesBottom ( a ) { var n = a . length ; var m = a [ 0 ] . length ; var q = [ ] ; for ( var i = 0 ; i < n ; i ++ ) { for ( var j = 0 ; j < m ; j ++ ) { if ( a [ i ] [ j ] == 1 ) { q . slice ( 0 , 0 , [ i , j , 1 ] ) ; } else if ( a [ i ] [ j ] == 2 ) { q . push ( [ i , j , 2 ] ) ; } a [ i ] [ j ] = 0 ; } } var dx = [ - 1 , 0 , 1 , 0 ] ; var dy = [ 0 , 1 , 0 , - 1 ] ; while ( ! q . length ) { var front = q [ 0 ] ; q . shift ( ) ; var i = front [ 0 ] , j = front [ 1 ] ; var t = front [ 2 ] ; if ( a [ i ] [ j ] ) continue ; a [ i ] [ j ] = 1 ; if ( t == 1 && ( i == n - 1 && j == m - 1 ) ) { return true ; } for ( var d = 0 ; d < 4 ; d ++ ) { var ni = i + dx [ d ] ; var nj = j + dy [ d ] ; if ( ni >= 0 && ni < n && nj >= 0 && nj < m ) { q . push ( [ ni , nj , t ] ) ; } } } return false ; } var matrix = [ [ 0 , 2 , 0 ] , [ 0 , 1 , 0 ] , [ 0 , 2 , 0 ] ] ; if ( reachesBottom ( matrix ) ) { document . write ( " " ) ; } else { document . write ( " " ) ; }