Easy Top Bottom Approch for noobs like me


#1
int Solution::solve(vector<vector<int> > &A) {

int n = A.size(),m=A[0].size();

int dp[n][m];

memset(dp,0,sizeof(dp));
dp[0][0]=1;

for(int i=0;i<n;i++)
{
    for(int j=0;j<m;j++)
    {
        if(i==0 and j==0)
        dp[i][j]=1;
        
        else if(i==0)
        {
            if(A[i][j]>A[i][j-1])
            {
                if(dp[i][j-1]!=0)
                dp[i][j]=1+dp[i][j-1];
            }
        }
        
        else if(j==0)
        {
            if(A[i][j]>A[i-1][j])
            {
                if(dp[i-1][j]!=0)
                dp[i][j]=1+dp[i-1][j];
            }
        }
        
        else
        {
            if(A[i][j]>A[i-1][j] and A[i][j] > A[i][j-1])
            {
                if(dp[i][j-1]!=0 or dp[i-1][j]!=0)
                dp[i][j]= 1 + max(dp[i][j-1],dp[i-1][j]);
            }
            else if(A[i][j]>A[i-1][j] and A[i][j]<A[i][j-1])
            {
                if(dp[i-1][j]!=0)
                dp[i][j]=1+dp[i-1][j];
            }
            else if(A[i][j]<A[i-1][j] and A[i][j]>A[i][j-1])
            {
                if(dp[i][j-1]!=0)
                dp[i][j]=1+dp[i][j-1];
            }
        }
    }
}
if(dp[n-1][m-1]==0)
return -1;
return dp[n-1][m-1];

}