Alternate swappin. it's not working for odd lenth
You code implementation is wrong and i am not able to understand your logic.
But you can do this in o(n^2)
For each element of the matrix, we try to find the number of sub-matrices, the element will lie in.
This can be done in O(1) time. Let us suppose the index of an element be (X, Y) in 0 based indexing, then the number of submatrices (Sx, y) for this element will be in can be given by the formula S(x, y) = (X + 1) * (Y + 1) * (N – X) * (N – Y) . This formula works, because we just have to choose two different positions on the matrix that will create a submatrix that envelopes the element. Thus, for each element, ‘sum’ can be updated as sum += (S(x, y)) * Arr(x, y) .
This is the implementation
int sum = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
int top = (i + 1) * (j + 1); // ways to choose from top-left elements
int bottom = (n - i) * (n - j); // ways to choose from bottom-right elements
sum += (top * bottom * arr[i][j]);
}
}
return sum;
i asked regarding alternate swapping of array element
for example 12345 will give output 21435
If question is this Alternate swappin then why you put it in Sum Of All Submatrix From A given Matrix the content.
But its ok.
First see this how i debug the code bu cout statement. See in the code
Then the correct code is in comment
still it’s not giving correct output
On which test case ?