BYTESM2 - Philosophers Stone - SPOJ Solution C++

  Problem Link : BYTESM2 


👉 Hint : Simple 2D DP

 


✅ C++ Solution :

 
#include<bits/stdc++.h>
using namespace std;

int dp[101][101];
int arr[101][101];
int main()
{
	int t,h,w;
	cin>>t;
	while(t--)
	{
		int x,y,z,ans=0;
		cin>>h>>w;
		memset(dp,0,sizeof(dp));
		for(int i=0;i<h;i++)
		{
			for(int j=0;j<w;j++)
				cin>>arr[i][j];
		}
		for(int i=0;i<w;i++)
			dp[h-1][i]=arr[h-1][i];
		for(int i=h-2;i>=0;i--)
		{
			for(int j=0;j<w;j++)
			{
				x=0,y=0;
				if(j-1>=0)
					x=dp[i+1][j-1];
				if(j+1<w)
					y=dp[i+1][j+1];
				dp[i][j]=arr[i][j]+max(y,max(dp[i+1][j],x));
				if(i==0)
					ans=max(ans,dp[i][j]);
			}

		}
		cout<<ans<<endl;
	}
}

 

Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook. 

😇Happy Learning!!