Length of longest connected 1 â €™ s in a Binary Grid | JavaScript program to implement the above approach ; Keeps a track of directions that is up , down , left , right ; Function to perform the dfs traversal ; Mark the current node as visited ; Increment length from this node ; Update the diameter length ; Move to next cell in x - direction ; Move to next cell in y - direction ; Check if cell is invalid then continue ; Perform DFS on new cell ; Decrement the length ; Function to find the maximum length of connected 1 s in the given grid ; Increment the id ; Traverse the grid [ ] ; Find start polet of start dfs call ; DFS Traversal from cell ( x , y ) ; Prlet the maximum length ; Given grid [ ] [ ] ; Function Call
let row = 6 ; let col = 7 ; let vis = new Array ( row + 1 ) ; for ( var i = 0 ; i < vis . length ; i ++ ) { vis [ i ] = new Array ( 2 ) ; } let id = 0 ; let diameter = 0 , length = 0 ; let x = 0 , y = 0 ; let dx = [ - 1 , 1 , 0 , 0 ] ; let dy = [ 0 , 0 , - 1 , 1 ] ; function dfs ( a , b , lis ) { vis [ a ] [ b ] = id ; length ++ ; if ( length > diameter ) { x = a ; y = b ; diameter = length ; } for ( let j = 0 ; j < 4 ; j ++ ) { let cx = a + dx [ j ] ; let cy = b + dy [ j ] ; if ( cx < 0 cy < 0 cx >= row cy >= col lis [ cx ] [ cy ] == 0 vis [ cx ] [ cy ] > 0 ) { continue ; } dfs ( cx , cy , lis ) ; } vis [ a ] [ b ] = 0 ; length -- ; } function findMaximumLength ( lis ) { id ++ ; length = 0 ; diameter = 0 ; for ( let i = 0 ; i < row ; i ++ ) { for ( let j = 0 ; j < col ; j ++ ) { if ( lis [ i ] [ j ] != 0 ) { dfs ( i , j , lis ) ; i = row ; break ; } } } id ++ ; length = 0 ; diameter = 0 ; dfs ( x , y , lis ) ; document . write ( diameter ) ; } let grid = [ [ 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 1 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 1 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 1 , 0 , 1 , 0 ] , [ 0 , 1 , 1 , 1 , 1 , 1 , 0 ] , [ 0 , 0 , 0 , 1 , 0 , 0 , 0 ] ] ; findMaximumLength ( grid ) ;