Length of longest connected 1 â €™ s in a Binary Grid | Python3 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
row = 6 NEW_LINE col = 7 NEW_LINE vis = [ [ 0 for i in range ( col + 1 ) ] for j in range ( row + 1 ) ] NEW_LINE id = 0 NEW_LINE diameter = 0 NEW_LINE length = 0 NEW_LINE dx = [ - 1 , 1 , 0 , 0 ] NEW_LINE dy = [ 0 , 0 , - 1 , 1 ] NEW_LINE def dfs ( a , b , lis , x , y ) : NEW_LINE INDENT global id , length , diameter NEW_LINE vis [ a ] [ b ] = id NEW_LINE length += 1 NEW_LINE if ( length > diameter ) : NEW_LINE INDENT x = a NEW_LINE y = b NEW_LINE diameter = length NEW_LINE DEDENT for j in range ( 4 ) : NEW_LINE INDENT cx = a + dx [ j ] NEW_LINE cy = b + dy [ j ] NEW_LINE if ( cx < 0 or cy < 0 or cx >= row or cy >= col or lis [ cx ] [ cy ] == 0 or vis [ cx ] [ cy ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT dfs ( cx , cy , lis , x , y ) NEW_LINE DEDENT vis [ a ] [ b ] = 0 NEW_LINE length -= 1 NEW_LINE return x , y NEW_LINE DEDENT def findMaximumLength ( lis ) : NEW_LINE INDENT global id , length , diameter NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE id += 1 NEW_LINE length = 0 NEW_LINE diameter = 0 NEW_LINE for i in range ( row ) : NEW_LINE INDENT for j in range ( col ) : NEW_LINE INDENT if ( lis [ i ] [ j ] != 0 ) : NEW_LINE INDENT x , y = dfs ( i , j , lis , x , y ) NEW_LINE i = row NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT id += 1 NEW_LINE length = 0 NEW_LINE diameter = 0 NEW_LINE x , y = dfs ( x , y , lis , x , y ) NEW_LINE print ( diameter ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT 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 ] ] NEW_LINE findMaximumLength ( grid ) NEW_LINE DEDENT