After a long time, here comes a post on parsing a NxN matrix. Our main intension here is to take the sum of the diagonals and take a absolute difference between them. At first, I simply forgot the C++ way to initialize an NxN array. Whoof!!
Let’s first understand what a double pointer is. It’s just a pointer to an array of pointers!!
What we do with a integer pointer *A? . Allocate an array of integers
Then what to do when u need a list of integer pointers **A ? Allocate an array of integer pointers
How its done?
Now below is the code to allocate the double pointer
Next confusion comes with reading this array diagonally. Until we understand how coordinates of an diagonal behave, it’s tough to understand that clearly.
If you see the left diagram, you can guess the paper work done for it.
From left->right, you can notice that always you get two indices, (i == j) equal. So you got this diagonal for all NxN.
From right –> left, what is the pattern ? It has to be the combination of i and j. If you see closely, i increases and j decreases as we move. i always increases in our loop, we just need to take care of making j to decrease.. or equating like this as well i+j = N+1 works!!
DISCLAIMER: There are better ways to do this on internet without O(N^2) loop. You can do this in a single loop as well.