GucciMane
GucciMane

Reputation: 23

How can I iterate over a 2D array without visiting an element more than once?

I would like to transpose a square matrix in place using a 2D array. However, when I iterate over the array using a nested for loop, the elements are visited twice causing no transpose to occur.

I would like to access each array element only once to correct this.

How could I alter my current code to do this?

// transpose in-place
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            int temp = a[i][j];
            a[i][j] = a[j][i];
            a[j][i] = temp;
        }
    }

Thank you.

Upvotes: 2

Views: 121

Answers (1)

samgak
samgak

Reputation: 24427

Change your inner loop condition to stop when j equals i:

for (int j = 0; j < i; j++)

This way you are only iterating over a triangular area of the matrix (formed by the values on one side of the diagonal defined by i = j), and swapping each value with the corresponding value on the other side of the diagonal.

Upvotes: 1

Related Questions