# 矩阵的“之”字形打印

2017-12-07 12:51:30来源:oschina作者:a_xianyu人点击

1234

5678

9 10 11 12

“之”字形打印的结果为：1,2,5,9,6,3,4,7,10,11,8,12

Solution:

public class Main {
public static final int N = 5;
public static final int MAX = 10;
public static void main(String[] args) {
int[][] m = new int[(int)(Math.random() * N + 1)][(int)(Math.random() * N + 1)];//矩阵大小随机
for (int i = 0; i < m.length; i++) { //矩阵中元素的值随机
for (int j = 0; j < m[i].length; j++) {
m[i][j] = (int)(Math.random() * MAX);
}
}
println(m);
printZ(m);
}
public static void printZ(int[][] m) { //矩阵“之”字形打印
System.out.print(m[0][0]);
int i = 0, j = 0;
int x1 = 0, y1 = 0, x2 = 0, y2 = 0;
boolean flag = false;
while(!(x1 == x2 && x1 == m.length - 1)) {
if (i++ < m[0].length - 1) {
y1 = i;
} else {
y1 = m[0].length - 1;
x1++;
}
if (j++ < m.length - 1) {
x2 = j;
} else {
y2++;
x2 = m.length - 1;
}
flag = flag ? false : true;
help(m, x1, y1, x2, y2, flag);
}
}
public static void help(int[][]m, int x1, int y1, int x2, int y2, boolean flag) {
if (flag) {
for (int i = x1; i <= x2; i++) {
System.out.print(" " + m[i][y1--]);
}
} else {
for (int i = x2; i >= x1; i--) {
System.out.print(" " + m[i][y2++]);
}
}
}
public static void println(int[][] m) { //输出矩阵的元素
for (int i = 0; i < m.length; i++) {
System.out.print(m[i][0]);
for (int j = 1; j < m[i].length; j++) {
System.out.print(" " + m[i][j]);
}
System.out.println();
}
System.out.println();
}
}

无相关信息