Find maximum path length in a binary matrix in Python

In this problem, we are given a square matrix mat[][] of size m X n with each element either 0 or 1. If an element has value 1, this means it is connected, if the value is 0, this means it is not-connected. Our task is to find the maximum path length in a binary matrix.

Problem Description − To solve the problem, we need to find the largest length path on the matrix, which means all 1 elements in the matrix. Before finding the path, we will convert at-most one 0 to 1.

Let’s take an example to understand the problem,


mat[][] = {{1, 0},
{0, 1}}




We can convert 0 at index (0, 1) or (1, 0) to maximise the path length.

Solution approach

A simple solution to the problem is by finding the length after converting each 0 to 1. We will use depth first search for finding the length of path and then return the maximum of all path lengths.

An efficient solution would be to eliminate the need to do multiple conversions and settle for one that gives the most promising solution. We will find a group such that switching one 0 to 1 will return the largest length path.

Program to illustrate the working of our solution,


 Live Demo

def FindNeighbor(R, C, N):
   for nr, nc in (((R - 1), C), ( (R + 1) , C), (R, (C - 1) ), (R, (C + 1) )):
      if 0 <= nr < N and 0 <= nc < N:
         yield nr, nc

def DFSTraversal(R, C, index, mat, N):
   maxLen = 1
   mat[R][C] = index
   for nr, nc in FindNeighbor(R, C, N):
      if mat[nr][nc] == 1:
         maxLen += DFSTraversal(nr, nc, index)

   return maxLen

def findLargestPath(mat):

   N = len(mat)
   maxPath = {}
   index = 2

   for i in range(N):
      for j in range(N):
         if mat[i][j] == 1:
            maxPath[index] = DFSTraversal(i, j, index, mat, N)
            index += 1

   maxPathLen = max(maxPath.values() or [0])

   for i in range(N):
      for j in range(N):
         if mat[i][j] == 0:
            seen = {mat[nr][nc] for nr, nc in FindNeighbor(i, j, N) if mat[nr][nc] > 1}
            maxPathLen = max(maxPathLen, 1 + sum(maxPath[i] for i in seen))

   return maxPathLen
I = [[1, 0], [0, 1]]
print("The length of largest path is " + str(findLargestPath(I)))


The length of largest path is 3