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
using System ; class GFG { static readonly int row = 6 ; static readonly int col = 7 ; static int [ , ] vis = new int [ row + 1 , col + 1 ] ; static int id ; static int diameter = 0 , length = 0 ; static int x = 0 , y = 0 ; static int [ ] dx = { - 1 , 1 , 0 , 0 } ; static int [ ] dy = { 0 , 0 , - 1 , 1 } ; static void dfs ( int a , int b , int [ , ] lis ) { 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 ] > 0 ) { continue ; } dfs ( cx , cy , lis ) ; } vis [ a , b ] = 0 ; length -- ; } static void findMaximumLength ( int [ , ] lis ) { 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 ) ; i = row ; break ; } } } id ++ ; length = 0 ; diameter = 0 ; dfs ( x , y , lis ) ; Console . Write ( diameter ) ; } public static void Main ( String [ ] args ) { int [ , ] 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 ) ; } }