# Program to find length of longest matrix path length in Python

PythonServer Side ProgrammingProgramming

Suppose we have a binary matrix, where 0 indicates empty cell and 1 indicates wall. We can start at any empty cell on first row and want to end up on any empty cell on the last row. We can move left, right, or down, we have to find the longest such path where we can visit each cell at most once. If this is not possible, then return 0.

So, if the input is like

 0 0 0 0 0 0 0 1 0 0 0 0

then the output will be 10, as We can move (0, 3), (0, 2), (0, 1), (0, 0), (1, 0), (1, 1), (1, 2), (2, 2), (2, 1), (2, 0).

To solve this, we will follow these steps −

• N := row count of matrix
• M := column count of matrix
• dp := a list of size M and fill with -1
• for i in range 0 to N - 1, do
• ndp := a list of size M and fill with -1
• ndp2 := a list of size M and fill with -1
• for j in range 0 to M - 1, do
• if matrix[i, j] is not 1 and (i is same as 0 or dp[j] > -1) , then
• ndp[j] := dp[j] + 1
• ndp2[j] := dp[j] + 1
• for j in range 1 to M - 1, do
• if matrix[i, j] is not 1 and ndp[j - 1] > -1, then
• ndp[j] := maximum of ndp[j] and (ndp[j - 1] + 1)
• for j in range M - 2 to 0, decrease by 1, do
• if matrix[i, j] is not 1 and ndp2[j + 1] > -1, then
• ndp2[j] := maximum of ndp2[j] and (ndp2[j + 1] + 1)
• ndp[j] := maximum of ndp[j] and ndp2[j]
• dp := ndp
• return (maximum of dp) + 1

## Example

Let us see the following implementation to get better understanding −

def solve(matrix):
N = len(matrix)
M = len(matrix)
dp = [-1 for i in matrix]
for i in range(N):
ndp = [-1 for j in matrix]
ndp2 = [-1 for j in matrix]
for j in range(M):
if matrix[i][j] != 1 and (i == 0 or dp[j] > -1):
ndp[j] = dp[j] + 1
ndp2[j] = dp[j] + 1

for j in range(1, M):
if matrix[i][j] != 1 and ndp[j - 1] > -1:
ndp[j] = max(ndp[j], ndp[j - 1] + 1)

for j in range(M - 2, -1, -1):
if matrix[i][j] != 1 and ndp2[j + 1] > -1:
ndp2[j] = max(ndp2[j], ndp2[j + 1] + 1)
ndp[j] = max(ndp[j], ndp2[j])

dp = ndp
return max(dp) + 1

matrix = [
[0, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]
]
print(solve(matrix))

## Input

[
[0, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]
]

## Output

10