Help me debug this code

Hey guys.

This time i want your help to trace the error in my code. The code is running on UNDEFINED behaviour, for reasons i am not able to guess.

This code is of problem KNICOV. I decided to make a matrix of size N x M , SUCH THAT-

 N is always greater than M.

If N < M, i will swap the values of N and M to make sure that N>M in all cases.

Then i made a nested loop, placing knights at places and marking positions where knights are (and are able to attack) as ‘1’.

The logic is-

if(arr[i][j]==0)
  Then place a knight here.
  Mark positions of knight where it may attack and where it is as '1'.
  Increment answer by 1.
  Repeat for entire 2-D array.

The code is-

#include <iostream>
using namespace std;
 
int main() {
	// your code goes here
	int t;
	cin>>t;
	while(t--)
	{
	    int n,m;
	    cin>>n>>m;
	   
	    int i,j;
	    int ans=0;
	    int maxd = n>m?n:m;
	    int mind=n<m?n:m;
	    n=maxd;
	    m=mind;//This is to make sure N>M for all cases.
	    int arr[n][m]={0};
	    //cout<<n<<" "<<m<<endl;//Critical Line 1.
	    for(i=0;i<n;i++) //The explanation is given above.
	    {
	        for(j=0;j<m;j++)
	        {
	            if(arr[i][j]==0)
	            {
	                //cout<<"I and J are "<<i<<" "<<j<<endl;//Critical Line 2.
	                ans++;
	                arr[i][j]=1;
	                if(i<n-2 && j>0)
	                  arr[i+2][j-1]=1;
	                if(i<n-2 && j<m-1)
	                  arr[i+2][j+1]=1;
	            }
	        }
	    }
	    cout<<ans<<endl;
	}
	return 0;
}

On the input-

1
2 2

The answer is 4. But its giving 3. Now, I have marked 2 critical lines in the code. They are currently as comments. When the lines are active, the code gives final answer as 4. When lines are deactivated by making them comments, it gives answer 3.

Nonetheless to say, i wasted a big deal of time on this Q in cook-off. I will appreciate if anyone will help me debug this :slight_smile:

Well, not a active C++ user myself.

But the problem is with your code is related to assigning zeros i.e. a[n][m] = {0}.

Reason for this can be found in this code.
No doubt if you run for loop for assigning and/or hard code like a[50][50] = {0}, things are working perfectly fine! :stuck_out_tongue:

1 Like

for me your code is giving 4 as answer

Run it only on codechef IDE, and make critical line 1 and 2 active by removing “//” in front of them. Undefined behaviour will behave differently on different compiler.

…Really? My logic was that, i read “If array is partially initialized, then all remaining valeus are set to 0 by default.”

Thanks a lot. Well, atleast i get to learn something from Cook-off. I remember someone warning me about this earlier, should ahve paid attention to it :frowning:

BTW, thanks a lot!!