Java面试_打印矩阵
按照上面图的要求打印矩阵,看一下要求,其实就是按照一定的规律遍历
一个二维数组,首先向右走一个单位,然后向左下,直到边界,然后向下,
右上知道边界。向右越界了就向下,向下越界了就向右,知道到达右下角。
翻译成代码逻辑
package swing;
public class JuZhen {
/**
* @param args
*/
public static void main(String[] args) {
int n = 4;
// 二维数组填充器 返回填充的二维数组下标和填充的数字
IndexGen g = new IndexGen(n);
int[][] nums = new int[n][n];
while (g.haveNext()) {
IndexInfo index = g.next();
nums[index.d1][index.d2] = index.num;
}
// 打印内容
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int pnum = nums[i][j];
String pnums = String.valueOf(pnum);
if (pnums.length() == 1)
pnums = " " + pnums;
System.out.print(pnums + " ");
}
System.out.println();
}
}
private static class IndexGen {
private IndexInfo currentIndex;
private int maxIndex;
private int count = 1;
private int totalNum;
private int flag = 1;
public IndexGen(int n) {
this.maxIndex = n - 1;
this.totalNum = n * n;
}
private boolean haveNext() {
if (count <= totalNum)
return true;
else
return false;
}
public IndexInfo next() {
// 起始状态
if (count == 1) {
currentIndex = new IndexInfo(0, 0);
currentIndex.num = count;
count++;
return currentIndex;
}
if (flag == 1) {
// 如果第二个下标达到最大值 向下 否则向右
if (currentIndex.isIndex2Max(maxIndex)) {
currentIndex = currentIndex.down();
} else
currentIndex = currentIndex.rigth();
flag++;
} else if