I have to traverse an n x n
matrix in java (so indices are 0,...,n-1), to assign values to the single elements. I must start from the bottom right and arrive to the top left. The particularity is that I do not have to consider the matrix[n-1][n-1]
element, that has been initialised before. The adjacent values depend on each other for initialazing and it must be initialized first.
One way could be inserting an if
in the for
cycle
for (i = n-1; i >= 0; i--)
for (j = n-1; j >= 0; j--)
if (i == n - 1 && j == n - 1)
//initialize particular value
else
//initialize others
but it seems to me a bit inefficient.
Another way could be to initialize the value matrix[n-1][n-1]
outside the cycle, then doing 3 for
cycles (one for the bottom line, one for the rightest column, one for the other elements). But it seems a bit inelegant.
So I'm searching, if exists, for a solution that involves only two annidate for
, and without a control in every cycle (like first example).
I think the solution of Joakim is good except the % and / operations... inspired to this, I've found an interesting variant that avoid them. I've called column index j1
to avoid problems with other "normal" cycles.
matrix[n-1][n-1] = //init code;
int j1 = n-2;
for (int i = n-1; i >= 0; i--) {
for (; j1 >= 0; j1--) {
matrix[i][j1] = //init code;
}
j1 = n-1;
}