Check for possible path in 2D matrix | JavaScript program to find if there is path from top left to right bottom ; To find the path from top left to bottom right ; Directions ; Queue ; Insert the top right corner . ; Until queue is empty ; Mark as visited ; Destination is reached . ; Check all four directions ; Using the direction array ; Not blocked and valid ; Given array ; Path from arr [ 0 ] [ 0 ] to arr [ row ] [ col ]
var row = 5 ; var col = 5 ; function isPath ( arr ) { var dir = [ [ 0 , 1 ] , [ 0 , - 1 ] , [ 1 , 0 ] , [ - 1 , 0 ] ] ; var q = [ ] ; q . push ( [ 0 , 0 ] ) ; while ( q . length > 0 ) { var p = q [ 0 ] ; q . shift ( ) ; arr [ p [ 0 ] ] [ p [ 1 ] ] = - 1 ; if ( p == [ row - 1 ] [ col - 1 ] ) return true ; for ( var i = 0 ; i < 4 ; i ++ ) { var a = p [ 0 ] + dir [ i ] [ 0 ] ; var b = p [ 1 ] + dir [ i ] [ 1 ] ; if ( a >= 0 && b >= 0 && a < row && b < col && arr [ a ] [ b ] != - 1 ) { q . push ( [ a , b ] ) ; } } } return false ; } var arr = [ [ 0 , 0 , 0 , - 1 , 0 ] , [ - 1 , 0 , 0 , - 1 , - 1 ] , [ 0 , 0 , 0 , - 1 , 0 ] , [ - 1 , 0 , - 1 , 0 , - 1 ] , [ 0 , 0 , - 1 , 0 , 0 ] ] ; if ( isPath ( arr ) ) document . write ( " " ) ; else document . write ( " " ) ;