Simple solution without recursion using dp


#1

Comment body goes here.


#2

int Solution::solve(vector<vector > &A) {
int n=A.size(),m=A[0].size();
vector<vector >dp(n,vector(m,-1));
dp[0][0]=1;
for(int i=1;i<m;i++){
if(A[0][i]>A[0][i-1])
dp[0][i]=1+dp[0][i-1];
}
for(int i=1;i<n;i++){
if(A[i][0]>A[i-1][0])
dp[i][0]=1+dp[i][0];
}
for(int i=1;i<n;i++){
for(int j=1;j<m;j++){
if(dp[i-1][j]==-1 && dp[i][j-1]==-1)
return -1;
if(A[i][j]>A[i-1][j]||A[i][j]>A[i][j-1])
dp[i][j]=1+max(dp[i-1][j],dp[i][j-1]);
}
}
if(dp[n-1][m-1]==0)
return -1;
return dp[n-1][m-1];

}


#3

Great approach, but it will fail on certain cases, because it pre-emptively exits, by checking if previous cells in path are both unreachable.

Consider this input: 4 4 1 2 3 4 2 2 1 4 3 1 3 4 4 5 6 7

A :
[
[1, 2, 3, 4]
[2, 2, 1, 4]
[3, 1, 3, 4]
[4, 5, 6, 7]
]

The expected output should be 7, but your approach will return -1.


#4

This code is not considering all the cases… InterviewBit test cases are weak…!
if a block is unreachable, that doesn’t means that we are unable to go to right corner(destination) . there may be other cases and paths also… please correct this solution… as it may create a misconception in someone’s mind :slight_smile: