java multi-dimensional array transposing

后端 未结 11 2161
谎友^
谎友^ 2020-12-10 11:42

I have a row-based multidimensional array:

/** [row][column]. */
public int[][] tiles;

I would like to transform this array to column-based

11条回答
  •  春和景丽
    2020-12-10 12:15

    I saw that all of the answers create a new resultant matrix. This is simple: matrix[i][j] = matrix[j][i]; However, you can also do this in-place, in case of square matrix.

    // Transpose, where m == n
    for(int i = 0; i < m; i++) {
      for(int j = i+1; j < n; j++) {
        int temp = matrix[i][j];
        matrix[i][j] = matrix[j][i];
        matrix[j][i] = temp;
      }
    }
    

    This is better for larger matrices, where creating a new resultant matrix is wasteful in terms of memory. If its not square, you can create a new one with NxM dimensions and do the out of place method. Note: for in-place, take care of j = i+1; Its not 0.

提交回复
热议问题