
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Length of Longest Matrix Path in Python
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
- if matrix[i, j] is not 1 and (i is same as 0 or dp[j] > -1) , then
- 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)
- if matrix[i, j] is not 1 and ndp[j - 1] > -1, then
- 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]
- if matrix[i, j] is not 1 and ndp2[j + 1] > -1, then
- 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[0]) dp = [-1 for i in matrix[0]] for i in range(N): ndp = [-1 for j in matrix[0]] ndp2 = [-1 for j in matrix[0]] 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
Advertisements