Length of longest connected 1 â €™ s in a Binary Grid | C ++ program for 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 point of start dfs call ; DFS Traversal from cell ( x , y ) ; Print the maximum length ; Driver Code ; Given grid [ ] [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE #define row  6 NEW_LINE #define col  7 NEW_LINE using namespace std ; int vis [ row + 1 ] [ col + 1 ] , id ; int diameter = 0 , length = 0 ; int dx [ ] = { -1 , 1 , 0 , 0 } ; int dy [ ] = { 0 , 0 , -1 , 1 } ; void dfs ( int a , int b , int lis [ ] [ col ] , int & x , int & y ) { vis [ a ] [ b ] = id ; length ++ ; if ( length > diameter ) { x = a ; y = b ; diameter = length ; } for ( int j = 0 ; j < 4 ; j ++ ) { int cx = a + dx [ j ] ; int cy = b + dy [ j ] ; if ( cx < 0 cy < 0 cx > = row cy > = col lis [ cx ] [ cy ] == 0 vis [ cx ] [ cy ] ) { continue ; } dfs ( cx , cy , lis , x , y ) ; } vis [ a ] [ b ] = 0 ; length -- ; } void findMaximumLength ( int lis [ ] [ col ] ) { int x , y ; id ++ ; length = 0 ; diameter = 0 ; for ( int i = 0 ; i < row ; i ++ ) { for ( int j = 0 ; j < col ; j ++ ) { if ( lis [ i ] [ j ] != 0 ) { dfs ( i , j , lis , x , y ) ; i = row ; break ; } } } id ++ ; length = 0 ; diameter = 0 ; dfs ( x , y , lis , x , y ) ; cout << diameter ; } int main ( ) { int grid [ ] [ col ] = { { 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 ) ; return 0 ; }