沿对角线交换NxN的二维数组的行、列数据
对角线往右的点,才需要交换;往左的点不用交换,避免重复交换。
public class Main {
private void print(int[][] arr){
for (int[] a:arr) {
for (int b: a) {
System.out.print(b+"\t");
}
System.out.println();
}
}
private void swap(int[][] arr){
int len = arr.length;
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
if (i<j) {
int temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
}
}
public static void main(String[] args) {
int[][] arr = new int[][]{{1,2,3,4,5},{11,12,13,14,15},{21,22,23,24,25},{31,32,33,34,35},{41,42,43,44,45}};
Main main = new Main();
main.print(arr);
main.swap(arr);
System.out.println();
main.print(arr);
}
}