Piyush and Magical park

Can you help me figure out what’s wrong with my code?

#include
using namespace std;
int main() {
int m,n,k,s;
cin>>m>>n>>k>>s;
//cout<<m<<n<<k<<s;

char a[m][n];
for(int i=0; i<m; i++)
{
	for(int j=0; j<m; j++)
	{
		cin>>a[i][j];
		//cout<<a[i][j]<<endl;
	}
}

int r = 0;
int c = 0;

while((r!=m-1 || c!=n-1) && s>0)
{
    //cout<<a[r][c]<<" "<<r<<c<<" ";
	if(a[r][c] == '.'){
		s = s-3;
		if(c<n-1)
        {
		    c++;
        }
		else
        {
            r++;
            c=0;
            s++;
        }
    }
	else if(a[r][c] == '*')
	{
		s = s+4;
		if(c<n-1)
        {c++;}
		else
		{
		    c=0;
            r++;
            s++;
		}
	}
	else if(a[r][c] == '#')
	{
		if(r<=m-2){
			r++;
			c=0;
		}
		else if(r == m-1){
			r = m-1;
			c = n-1;
			break;
		}
	}

	//cout<<s<<endl;
}

if(s>k){
	cout<<"Yes"<<endl;
	cout<<s;
}
else{
	cout<<"No";
	//cout<<s;
}

return 0;

}

Here’s the new code, it fails 2 test cases.

#include
using namespace std;
int main() {
int m,n,k,s;
cin>>m>>n>>k>>s;
//cout<<m<<n<<k<<s;

char a[m][n];
for(int i=0; i<m; i++)
{
	for(int j=0; j<m; j++)
	{
		cin>>a[i][j];
		//cout<<a[i][j]<<endl;
	}
}

int r = 0;
int c = 0;

while((r!=m-1 || c!=n-1) && s>=k)
{
    //cout<<a[r][c]<<" "<<r<<c<<" ";
	if(a[r][c] == '.'){
		s = s-3;
		if(c<n-1)
        {
		    c++;
        }
		else
        {
            r++;
            c=0;
            s++;
        }
    }
	else if(a[r][c] == '*')
	{
		s = s+4;
		if(c<n-1)
        {c++;}
		else
		{
		    c=0;
            r++;
            s++;
		}
	}
	else if(a[r][c] == '#')
	{
		if(r<=m-2){
			r++;
			c=0;
		}
		else if(r == m-1){
			r = m-1;
			c = n-1;
			break;
		}
	}

	//cout<<s<<endl;
}

if(s>=k){
	cout<<"Yes"<<endl;
	cout<<s;
}
else{
	cout<<"No";
	//cout<<s;
}

return 0;

}

in checks where you check for out of bounds, first increment and then check, since you already accounted for the current cell and need to check whether moving the next is valid or not
currently you are checking for the current cell to be in bound and if yes it increments which then goes out of bound so in the next iteration a check is made on a garbage value
secondly, s should always be greater than k not just at the end

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.