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 ; set arr [ 0 ] [ 0 ] = 1 ; Mark reachable ( from top left ) nodes in first row and first column . ; Mark reachable nodes in remaining matrix . ; return yes if right bottom index is 1 ; Given array ; path from arr [ 0 ] [ 0 ] to arr [ row ] [ col ]
var arr = [ [ 5 ] , [ 5 ] ] function isPath ( arr ) { arr [ 0 ] [ 0 ] = 1 ; for ( var i = 1 ; i < 5 ; i ++ ) if ( arr [ i ] [ 0 ] != - 1 ) arr [ i ] [ 0 ] = arr [ i - 1 ] [ 0 ] ; for ( var j = 1 ; j < 5 ; j ++ ) if ( arr [ 0 ] [ j ] != - 1 ) arr [ 0 ] [ j ] = arr [ 0 ] [ j - 1 ] ; for ( var i = 1 ; i < 5 ; i ++ ) for ( var j = 1 ; j < 5 ; j ++ ) if ( arr [ i ] [ j ] != - 1 ) arr [ i ] [ j ] = Math . max ( arr [ i ] [ j - 1 ] , arr [ i - 1 ] [ j ] ) ; return ( arr [ 5 - 1 ] [ 5 - 1 ] == 1 ) ; } 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 ( " " ) ;