Find maximum path length in a binary matrix in Python

In this problem, we are given a square matrix of size m × n with each element either 0 or 1. If an element has value 1, it represents a connected cell; if the value is 0, it represents a disconnected cell. Our task is to find the maximum path length in a binary matrix by converting at most one 0 to 1.

Problem Description

To solve this problem, we need to find the largest length path consisting of all connected cells (1s) in the matrix. We can convert at most one 0 to 1 to maximize the path length. The path can move in four directions: up, down, left, and right.

Example

Input

matrix = [[1, 0],
          [0, 1]]

Output

3

Explanation

We can convert the 0 at index (0, 1) or (1, 0) to 1, which connects both diagonal 1s, creating a path of length 3.

Solution Approach

The algorithm works in two phases:

  1. Group Formation: Use DFS to find all connected components of 1s and assign each group a unique identifier
  2. Optimal Conversion: For each 0, calculate the potential path length if we convert it to 1 by summing the sizes of adjacent groups

Implementation

def find_neighbors(row, col, n):
    """Find valid neighboring cells"""
    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    for dr, dc in directions:
        nr, nc = row + dr, col + dc
        if 0 <= nr < n and 0 <= nc < n:
            yield nr, nc

def dfs_traversal(row, col, group_id, matrix, n):
    """Perform DFS to find connected component size"""
    if matrix[row][col] != 1:
        return 0
    
    matrix[row][col] = group_id
    size = 1
    
    for nr, nc in find_neighbors(row, col, n):
        if matrix[nr][nc] == 1:
            size += dfs_traversal(nr, nc, group_id, matrix, n)
    
    return size

def find_largest_path(matrix):
    """Find maximum path length after converting at most one 0 to 1"""
    n = len(matrix)
    # Create a copy to avoid modifying original matrix
    mat = [row[:] for row in matrix]
    
    group_sizes = {}
    group_id = 2  # Start from 2 (0 and 1 are reserved)
    
    # Phase 1: Find all connected components
    for i in range(n):
        for j in range(n):
            if mat[i][j] == 1:
                size = dfs_traversal(i, j, group_id, mat, n)
                group_sizes[group_id] = size
                group_id += 1
    
    # Get maximum existing path length
    max_path_length = max(group_sizes.values()) if group_sizes else 0
    
    # Phase 2: Try converting each 0 to 1
    for i in range(n):
        for j in range(n):
            if mat[i][j] == 0:
                # Find unique adjacent groups
                adjacent_groups = set()
                for nr, nc in find_neighbors(i, j, n):
                    if mat[nr][nc] > 1:
                        adjacent_groups.add(mat[nr][nc])
                
                # Calculate new path length
                new_length = 1 + sum(group_sizes[group] for group in adjacent_groups)
                max_path_length = max(max_path_length, new_length)
    
    return max_path_length

# Test the function
matrix = [[1, 0], [0, 1]]
result = find_largest_path(matrix)
print(f"The length of largest path is {result}")
The length of largest path is 3

How It Works

  1. DFS Grouping: Each connected component of 1s gets assigned a unique group ID (starting from 2)
  2. Size Tracking: We store the size of each group in a dictionary
  3. Zero Conversion: For each 0, we check its neighbors and sum the sizes of adjacent groups
  4. Maximum Calculation: We return the maximum between existing paths and potential new paths

Time and Space Complexity

  • Time Complexity: O(n²) where n is the matrix dimension
  • Space Complexity: O(n²) for the matrix copy and group storage

Conclusion

This algorithm efficiently finds the maximum path length by grouping connected components and evaluating the benefit of converting each 0 to 1. The two-phase approach avoids redundant calculations and provides an optimal solution.

Updated on: 2026-03-25T17:27:31+05:30

355 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements