Longest Matrix Path Length - Google Top Interview Questions
Problem Statement :
You are given a two dimensional integer matrix where 0 is an empty cell and 1 is a wall. You can start at any empty cell on row 0 and want to end up on any empty cell on row n - 1. Given that you can move left, right, or down, return the longest such path where you visit each cell at most once. If there is no viable path, return 0. Constraints 1 ≤ n * m ≤ 200,000 where n and m are the number of rows and columns in matrix. Example 1 Input matrix = [ [0, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0] ] Output 10 Explanation We can move (0, 0), (0, 1), (0, 2), (0, 3), (1, 3), (1, 2), (1, 1), (2, 1), (2, 2), (2, 3).
Solution :
Solution in C++ :
bool isValid(int i, int j, int n, int m) {
if (i >= 0 && i < n && j >= 0 && j < m) return true;
return false;
}
// 0->left,1->right,2->down
// left = i,j-1
// down = i+1,j
// right = i,j+1
int rec(int f, int i, int j, vector<vector<int>>& mat, vector<vector<vector<int>>>& dp, int n,
int m) {
if (i == n - 1) {
if (f == 0 && j == 0) return 0;
if (f == 1 && j == m - 1) return 0;
}
int& ans = dp[f][i][j];
if (ans != -2) return ans;
ans = 0;
if (f == 0) {
// I am in left direction ,hence I can only go left and down
if (isValid(i, j - 1, n, m) && mat[i][j - 1] == 0)
ans = 1 + rec(0, i, j - 1, mat, dp, n, m);
if (isValid(i + 1, j, n, m) && mat[i + 1][j] == 0)
ans = max(ans, 1 + rec(2, i + 1, j, mat, dp, n, m));
} else if (f == 1) {
// I am in right direction , hence I can only go further right and down
if (isValid(i, j + 1, n, m) && mat[i][j + 1] == 0)
ans = 1 + rec(1, i, j + 1, mat, dp, n, m);
if (isValid(i + 1, j, n, m) && mat[i + 1][j] == 0)
ans = max(ans, rec(2, i + 1, j, mat, dp, n, m) + 1);
} else {
// now I am in downward direction hence I can go in all three directions
// cout<<"hel";
if (isValid(i, j + 1, n, m) && mat[i][j + 1] == 0)
ans = 1 + rec(1, i, j + 1, mat, dp, n, m);
if (isValid(i + 1, j, n, m) && mat[i + 1][j] == 0) {
ans = max(ans, 1 + rec(2, i + 1, j, mat, dp, n, m));
// cout<<"hey";
}
if (isValid(i, j - 1, n, m) && mat[i][j - 1] == 0)
ans = max(ans, 1 + rec(0, i, j - 1, mat, dp, n, m));
}
// cout<<ans;
if (ans == 0 && i != n - 1) return ans = -1;
return ans;
}
int solve(vector<vector<int>>& mat) {
int n = mat.size();
if (!n) return 0;
int m = mat[0].size();
// cout<<n<<endl;
vector<vector<vector<int>>> dp(3, vector<vector<int>>(n, vector<int>(m, -2)));
int ans = 0;
for (int j = 0; j < m; j++) {
if (mat[0][j] == 1) continue;
// cout<<"hello
";
// cout<<rec(2,0,j,mat,dp,n,m);
ans = max(ans, 1 + rec(2, 0, j, mat, dp, n, m));
}
return ans;
}
Solution in Java :
import java.util.*;
class Solution {
public int solve(int[][] matrix) {
int N = matrix.length;
int M = matrix[0].length;
int[][] dp = new int[N + 1][M];
for (int i = 0; i < N; i++) Arrays.fill(dp[i], Integer.MIN_VALUE);
for (int i = N - 1; i >= 0; i--) {
for (int j = 0; j < M; j++) {
if (matrix[i][j] == 1)
continue;
for (int k = j; k >= 0; k--) {
if (matrix[i][k] == 1)
break;
int x = 1 + Math.abs(j - k);
dp[i][j] = Math.max(dp[i][j], x + dp[i + 1][k]);
}
for (int k = j; k < M; k++) {
if (matrix[i][k] == 1)
break;
int x = 1 + Math.abs(j - k);
dp[i][j] = Math.max(dp[i][j], x + dp[i + 1][k]);
}
}
}
int ans = 0;
for (int j = 0; j < M; j++) ans = Math.max(ans, dp[0][j]);
return ans;
}
}
Solution in Python :
class Solution:
def solve(self, matrix):
rows = len(matrix)
cols = len(matrix[0])
ninf = -1000000000
@cache
def dfs(x, y, dy):
if x == rows:
return 0
if matrix[x][y] == 1:
return ninf
best = ninf
if dy == 0:
best = max(best, dfs(x, y, 1))
best = max(best, dfs(x, y, -1))
elif 0 <= y + dy < cols:
best = max(best, dfs(x, y + dy, dy) + 1)
best = max(best, dfs(x + 1, y, 0) + 1)
return best
best = 0
for y in range(cols):
best = max(best, dfs(0, y, 0))
return best
View More Similar Problems
Tree Coordinates
We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For
View Solution →Array Pairs
Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .
View Solution →Self Balancing Tree
An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ
View Solution →Array and simple queries
Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty
View Solution →Median Updates
The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o
View Solution →Maximum Element
You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each
View Solution →