2 回答
TA贡献1799条经验 获得超8个赞
你可以这样做:
public static int[][] rearrange(int[][] input) {
int rows = input.length, cols = input[0].length, total = rows * cols;
int[][] output = new int[rows][cols];
for (int i = 0; i < total; i++)
output[i / cols][i % cols] = input[i % rows][i / rows];
return output;
}
测试
int[][] input = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {13, 14, 15}, {16, 17, 18}, {19, 20, 21}};
System.out.println(Arrays.deepToString(rearrange(input)));
输出
[[1, 4, 7], [10, 13, 16], [19, 2, 5], [8, 11, 14], [17, 20, 3], [6, 9, 12], [15, 18, 21]]
TA贡献1856条经验 获得超5个赞
或者像这样:
for (int j = 0, p = 0; j < 7; j++) {
for (int i = 0; i < 3; i++, p++) {
newMatrix[j][i] = oldMatrix[p % 7][p / 7];
}
}
添加回答
举报