Suppose you have to collect maximum diamonds on your path from 0,0 to (n-1,m-1) then go back from (n-1,m-1) to (0,0) diamond values can be 1,0,-1. where -1 represent that you cannot go in that cell. additionally once a diamond is collected it cannot be collected again. while solving this I was thinking if going from top to bottom is same as the bottom to the top ?? To check this I wrote a code and tried a lot of cases but all of them are giving the same answer, still, i firmly believe that there should be the difference in some of the cases. Can somebody enlighten me how to prove that both are same or different??
If you want to check answer you can run this code. just change the value of grid.
<a href="https://ide.geeksforgeeks.org/ND8zWWA55m"></a>
Thankyou
#include<bits/stdc++.h>
using namespace std;
int bottomup(vector<vector<int>> g){
vector<vector<int>> t = g;
int n = t.size() , m = t[0].size();
for(int i=n-1 ; i>=0 ; i--){
if(t[i][m-1] == -1){
for(int j=i-1 ; j>=0 ; j--)t[j][m-1] = -1;
break;
}
if(i == n-1)continue;
t[i][m-1] += t[i+1][m-1];
}
for(int i=m-1 ; i>=0 ; i--){
if(t[n-1][i] == -1){
for(int j=i-1 ; j>=0 ; j--)t[n-1][j] = -1;
break;
}
if(i == m-1)continue;
t[n-1][i] += t[n-1][i+1];
}
for(int i=n-2 ; i>=0 ; i--){
for(int j=m-2 ; j>=0 ; j--){
if((t[i][j+1] == -1 && t[i+1][j] == -1) || t[i][j] == -1)t[i][j]=-1;
else
t[i][j] = max(t[i][j+1] , t[i+1][j])+t[i][j];
}
}
for(int i=0 ; i<n ; i++){
for(int j=0 ; j<m ; j++){
cout<<t[i][j]<<",";
}
cout<<endl;
}
if(t[0][0] == -1)return -1;
else return t[0][0];
}
int findmax(vector<vector<int>> g){
vector<vector<int>> t = g;
for(int i=0 ; i<t.size() ; i++){
if(t[i][0] == -1){
for(int j=i+1 ; j<t.size() ; j++)t[j][0] = -1;
break;
}
if(i ==0)continue;
t[i][0] += t[i-1][0];
}
for(int i=0 ; i<t[0].size() ; i++){
if(t[0][i] == -1){
for(int j=i+1 ; j<t[0].size() ; j++)t[0][j] = -1;
break;
}
if(i== 0) continue;
t[0][i] += t[0][i-1];
}
for(int i=1 ; i<t.size() ; i++){
for(int j=1 ; j<t[0].size() ; j++){
if((t[i-1][j] == -1 && t[i][j-1] == -1) || t[i][j] == -1)t[i][j]=-1;
else
t[i][j] = max(t[i-1][j] , t[i][j-1])+t[i][j];
}
}
int n = t.size() , m = t[0].size();
for(int i=0 ; i<n ; i++){
for(int j=0 ; j<m ; j++){
cout<<t[i][j]<<",";
}
cout<<endl;
}
if(t[t.size()-1][t[0].size()-1] == -1)return -1;
else return t[n-1][m-1];
}
int main(){
vector<vector<int>> g =
{{1,10,2,3,5},
{-1,2,1,1,3},
{20,1,2,-1,6},
{3,2,1,1,8}
};
findmax(g);cout<<endl;
bottomup(g);
}