forked from prakashshuklahub/Interview-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Increasing Path in Matrix
55 lines (38 loc) · 1.3 KB
/
Increasing Path in Matrix
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
Problem Description
Given a 2D integer matrix A of size N x M.
From A[i][j] you can move to A[i+1][j], if A[i+1][j] > A[i][j], or can move to A[i][j+1] if A[i][j+1] > A[i][j].
The task is to find and output the longest path length if we start from (0, 0).
NOTE:
If there doesn't exist a path return -1.
public int solve(int[][] A) {
int[][]dp = new int[A.length][A[0].length];
dp[0][0] = 1;
for(int i=1;i<A[0].length;i++){
if(A[0][i]>A[0][i-1]){
dp[0][i] = dp[0][i-1]+1;
}else{
break;
}
}
for(int i=1;i<A.length;i++){
if(A[i][0]>A[i-1][0]){
dp[i][0] = dp[i-1][0]+1;
}else{
break;
}
}
for(int i=1;i<A.length;i++){
for(int j=1;j<A[0].length;j++){
if(A[i][j]>A[i-1][j] && dp[i-1][j]!=0){
dp[i][j] = dp[i-1][j]+1;
}
if(A[i][j]>A[i][j-1] && dp[i][j-1]!=0){
dp[i][j] = Math.max(dp[i][j-1]+1,dp[i][j]);
}
}
}
int n = A.length-1;
int m = A[0].length-1;
if(dp[n][m]==0)return -1;
else return dp[n][m];
}