let's suppose that we have a simmetric matrix.
A=
1 2 3
2 6 4
3 4 5
now since it's simmetric we don't need to store memorize all the numbers in it. Let's assume to put 0 in the cells of the left lower triangle.
B =
1 2 3
0 6 4
0 0 5
if i want to access the the content of a 0 element of B all i need to do is invert row and col of the interested cell :
if(i>j) val += L[j][i] // ex: B[1][0] is stored in B[0][1]
(let's suppose the goal is to sum all the non-memorized elements)
at this point we are only using the upper right triangle, but we are not actually saving memory, because the unused elements are still allocated with 0 value.
one way to save memory is to use a vector of vectors :
vector<vector<int>> C;
and resize each row accordingly.
C=
1 2 3
6 4
5
By doing this tough, we cannot use the swap trick anymore, because as you may notice the empty elements are now in the bottom right triangle of the matrix.
the unallocated values are then:
D=
x x x
x x 2
x 3 4
in this case the elements we are interested in can be found with this if condition:
if(j >= size - i)
now the problem is to identify the correct content of the 0 elements. In other words:
if(j >= size - i) ans += L[?][?]
so for example if i'm at i=1 j=2 i should not access to the element [1][2] but instead to [0][2] = 2 ( and so on [2][1] -> [0][2] = 3, [2][2] -> [1][1] = 4).
how is it possible to achieve it ?