51,412
社区成员
发帖
与我相关
我的任务
分享int[][] a = {{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}};
int h=a.length;//矩形高
int w=a[0].length;//宽
for(int i=0;i<h+w-1;i++)
for(int y=i<h?i:h-1,x=i-y;y>=0&&x<w;x++){
System.out.println(a[y][x]);
y--;
}
2. 个人感觉这种比第一种稍微复杂一点.但这种比较符合面向对象的思维. 将x , y 坐标以及值 组成对象. 把二维数组转成 对象列表. 再对列表进行排序. x+y 小的排在前面, 如果x+y相等 则把 x小的排在前面. 代码如下:
import java.util.*;
public class Test {
public static void main(String[] args) {
int[][] a = {{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}};
List<Test> ts = new ArrayList<>();
for(int i=0;i<a.length;i++){
for(int j=0;j<a[0].length;j++){
ts.add(new Test(j,i,a[i][j]));
}
}
ts.sort((o1,o2)-> o1.x+o1.y!=o2.x+o2.y ? o1.x+o1.y-(o2.x+o2.y) : o1.x-o2.x );
for(Test v : ts)
System.out.println(v.value);
}
int x;
int y;
int value;
Test(int x,int y ,int value){
this.x=x;
this.y=y;
this.value=value;
}
}