I have used the logic in the editorial but I have made some mistake in it. I searched but couldn’t find it. Please help

Hey dragonemperor, you can refer to the editorial of the problem here. It will help you understand the mistake you are making.

I think the problem lies in your implementation regarding finding the initial matrix. You should use another matrix to find the matrix C, described in the editorial. Since you are finding the matrix in the same matrix itself the values are been modified and the 2nd loop you execute stores faulty values.

Here is a link to my solution https://www.codechef.com/viewsolution/7944592