Doubt on Matrix Problem

I did this problem on CodeForces
Link-https://codeforces.com/contest/1422/problem/B
Code Link-https://ide.codingblocks.com/s/350460

My code is working fine for many test cases but also failing for some.It would be really nice if you could help me with this.I dry run my logic it was working fine and I have no idea why it’s failing.

hello @mridulmohanbagri17
ur approach is almost correct .
image

this part might be creating issue ,
the idea is to pick mid element among the four and make other 3 values same as 1st.

thats it
check this easy implementation->

int ans = 0;
		for(int i = 1; i <= n; i++)
		{
			for(int j = 1; j <= m; j++)
			{
				vector<int> v = {a[i][j], a[i][m - j + 1], a[n - i + 1][j], a[n - i + 1][m - j + 1]};
				sort(v.begin(), v.end());
				int val = v[1];
				ans += abs(a[i][j] - val);
				a[i][j] = val;
				ans += abs(a[i][m - j + 1] - val);
				a[i][m - j + 1] = val;
				ans += abs(a[n - i + 1][j] - val);
				a[n - i + 1][j] = val;
				ans += abs(a[i][j] - val);
				a[i][m - j + 1] = val;
			}
		}
		cout << ans << endl;

instead of v[1] ,v[2] can also be taken right?

yeah,
u can take either v[1] or v[2] or ( v[1]+v[2])/2

1 Like

And sorry I have one more question ,if we iterate for all the elements in the matrix ,won’t the answer get added 4 times .

no when u will encounter first time then u will make 4 element same and u will add its change to ur answer.
next time when u will encounter then there will be no change becuase all 4 will be equal now so net change it will add is 0.

1 Like

Thankyou very much I understood the point.I forgot that we are changing the elements of the matrix.Sorry