public class T4{
public static void main(String args[]){
int data[][]=new int[][]{{1,2,3},{4,5,6},{7,8,9}};
inverse(data);
print(data);
}
public static void inverse(int temp[][]){
for (int x=0;x<temp.length ;x++ ) {
//y=x是一个关键的问题
//在这里如果写y=0最后的转置的结果会和输入一样举例:
//第一组循环 0,0——0,0
// 0,1——1,0
// 0,2——2,1
// 第二组循环 1,0——0,1 很明显在这里将第一次循环中的数据又给重置了
// 正确的应为:
// 第一组循环 0,0——0,0
// 0,1——1,0
// 0,2——2,0
// 第二组循环 1,1——1,1
// 1,2——2,1
// 第三组循环 2,2——2,2
// 共进行了3次数据的有效交换,也就是影响到了6组数据,还有3次数据不用交换
// 共计6+3=9组数据重置完成
for (int y=x;y<temp[x].length ;y++ ) {
int a=0;
if(x!=y){
a=temp[x][y];
temp[x][y]=temp[y][x];
temp[y][x]=a;
}
}
}
}
public static void print(int temp[][]){
for (int x=0;x<temp.length ;x++ ) {
for (int y=0;y<temp.length ;y++ ) {
System.out.print(temp[x][y]+"\t");
}
System.out.println();//换行的作用
}
}
}
二维数组的转置
猜你喜欢
转载自blog.csdn.net/guohaocan/article/details/80993259
今日推荐
周排行