Minimum initial vertices to traverse whole matrix with given conditions | Javascript program to find minimum initial vertices to reach whole matrix . ; ( n , m ) is current source cell from which we need to do DFS . N and M are total no . of rows and columns . ; Marking the vertex as visited ; If below neighbor is valid and has value less than or equal to current cell 's value ; If right neighbor is valid and has value less than or equal to current cell 's value ; If above neighbor is valid and has value less than or equal to current cell 's value ; If left neighbor is valid and has value less than or equal to current cell 's value ; Storing the cell value and cell indices in a vector . ; Sorting the newly created array according to cell values ; Create a visited array for DFS and initialize it as false . ; Applying dfs for each vertex with highest value ; If the given vertex is not visited then include it in the set ; driver code
var MAX = 100 ; function dfs ( n , m , visit , adj , N , M ) { visit [ n ] [ m ] = 1 ; if ( n + 1 < N && adj [ n ] [ m ] >= adj [ n + 1 ] [ m ] && ! visit [ n + 1 ] [ m ] ) dfs ( n + 1 , m , visit , adj , N , M ) ; if ( m + 1 < M && adj [ n ] [ m ] >= adj [ n ] [ m + 1 ] && ! visit [ n ] [ m + 1 ] ) dfs ( n , m + 1 , visit , adj , N , M ) ; if ( n - 1 >= 0 && adj [ n ] [ m ] >= adj [ n - 1 ] [ m ] && ! visit [ n - 1 ] [ m ] ) dfs ( n - 1 , m , visit , adj , N , M ) ; if ( m - 1 >= 0 && adj [ n ] [ m ] >= adj [ n ] [ m - 1 ] && ! visit [ n ] [ m - 1 ] ) dfs ( n , m - 1 , visit , adj , N , M ) ; } function printMinSources ( adj , N , M ) { var x = [ ] ; for ( var i = 0 ; i < N ; i ++ ) for ( var j = 0 ; j < M ; j ++ ) x . push ( [ adj [ i ] [ j ] , [ i , j ] ] ) ; x = x . sort ( ) ; var visit = new Array ( N ) ; for ( var i = 0 ; i < N ; i ++ ) { visit [ i ] = [ ] ; for ( var j = 0 ; j < MAX ; j ++ ) { visit [ i ] . push ( false ) ; } } for ( var i = x . length - 1 ; i >= 0 ; i -- ) { if ( ! visit [ x [ i ] [ 1 ] [ 0 ] ] [ x [ i ] [ 1 ] [ 1 ] ] ) { document . write ( x [ i ] [ 1 ] [ 0 ] + " " + x [ i ] [ 1 ] [ 1 ] + " " ) ; dfs ( x [ i ] [ 1 ] [ 0 ] , x [ i ] [ 1 ] [ 1 ] , visit , adj , N , M ) ; } } } var N = 2 var M = 2 var adj = [ [ 3 , 3 ] , [ 1 , 1 ] ] printMinSources ( adj , N , M )