时间限制:3秒 空间限制:32768K
热度指数:1160
本题知识点: 数组
题目描述
有一个二维数组(n*n),写程序实现从右上角到左下角沿主对角线方向打印。
给定一个二位数组arr及题目中的参数n,请返回结果数组。
测试样例
[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]],4
返回
[4,3,8,2,7,12,1,6,11,16,5,10,15,9,14,13]
代码:
import java.util.*;
//比较器
class Comparators {
public static Comparator getComparator() {
return new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof Integer) {
return compare( (Integer) o1, (Integer) o2);
} else return 1;
}
public int compare(Integer s1, Integer s2) {
return s2-s1;
}
};
}
}
public class Main {
public static int[] arrayPrint(int[][] arr, int n) {
// write code here
int[] ans = new int[n*n];
int x = 0, y = n-1;
int num = 0;
int flag = 0;
for(int i = 0; i < 2*n-1; i++) {
int xx = x, yy = y;
while(xx!=n && yy!=n) {
ans[num++] = arr[xx][yy];
xx++;
yy++;
}
if(x == 0 && y == 0){
x = 1;
flag = 1;
}
else{
if(flag == 0) {
x = (x != 0 ? x-1 : 0);
y = (y != 0 ? y-1 : 0);
} else {
x = (x != 0 ? x+1 : 0);
y = (y != 0 ? y+1 : 0);
}
}
}
return ans;
}
/*
测试代码
*/
public static void main(String []args){
/*Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
}*/
int[][] arr = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16}};
int n = 4;
int[] ans = arrayPrint(arr, n);
for(int i = 0; i < n*n; i++) {
System.out.print(ans[i]+" ");
}
System.out.println();
}
}