程序代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
package
chapter02;
import
java.util.Arrays;
/*
* 矩阵转置的实现(简单版)
*/
public
class
CH02_04 {
public
static
void
main(String[] args) {
int
[][] arr =
{
{
1
,
2
,
3
},
{
4
,
5
,
6
},
{
7
,
8
,
9
}
};
int
rows = arr.length;
int
cols = arr[
0
].length;
int
[][] arrResult =
new
int
[cols][rows];
//填充结果数组
for
(
int
i =
0
; i < arrResult.length; i++){
Arrays.fill(arrResult[i],
0
);
}
//输出矩阵转置前的矩阵
for
(
int
i =
0
; i < arr.length; i++){
System.out.println(Arrays.toString(arr[i]));
}
//转置矩阵
for
(
int
i =
0
; i < rows; i++){
//外循环,从原来矩阵的第i行开始
for
(
int
j =
0
; j < cols; j++){
//内循环,转置矩阵
arrResult[j][i] = arr[i][j];
}
}
System.out.println();
//输出转置后的矩阵
for
(
int
i =
0
; i < arrResult.length; i++){
System.out.println(Arrays.toString(arrResult[i]));
}
}
}
|
执行结果如下:
1
2
3
4
5
6
7
|
[
1
,
2
,
3
]
[
4
,
5
,
6
]
[
7
,
8
,
9
]
[
1
,
4
,
7
]
[
2
,
5
,
8
]
[
3
,
6
,
9
]
|
本文转自 xpleaf 51CTO博客,原文链接:http://blog.51cto.com/xpleaf/1976528,如需转载请自行联系原作者