日期:2014-05-20  浏览次数:20858 次

如何形成以下数组并打印出来?
1 2 9 10 25
 4 3 8 11 24
 5 6 7 12 23
16 15 14 13 22
17 18 19 20 21

------解决方案--------------------
Java code
/**
 * “蛇形矩阵” 计算及打印
 * @author SageZk
 * @version 1.0
 */
public class Sp {

    public static void main(String[] args) {
        //方阵计算
        final int LEN = 69;  //元素个数
        final int SIDE = (int) Math.ceil(Math.sqrt(LEN));
        final int[][] M = new int[SIDE][SIDE];
        for (int i = 1, r = 0, c = 0, flag = 'c'; i <= LEN;) {
            M[r][c] = i++;
            if (r == 0) {
                if (c % 2 == 0) ++c;
                else ++r;
                continue;
            }
            if (c == 0) {
                if (r % 2 == 1) ++r;
                else ++c;
                continue;
            }
            switch (flag) {
            case 'c':
                if (c % 2 == 0) {
                    --r;
                } else {
                    if (M[r][c - 1] != 0) {
                        ++r;
                    } else {
                        --c;
                        flag = 'r';
                    }
                }
                break;
            case 'r':
                if (r % 2 == 1) {
                    --c;
                } else {
                    if (M[r - 1][c] != 0) {
                        ++c;
                    } else {
                        --r;
                        flag = 'c';
                    }
                }
                break;
            }
        }
        //打印输出
        final int PWIDTH = Integer.toString(LEN, 10).length();
        final String FORMAT = "%0$" + PWIDTH + "d ";
        final String FSPACE = "%0$" + PWIDTH + "s ";
        for (int r = 0; r < M.length; ++r) {
            for (int c = 0; c < M[r].length; ++c) {
                if (M[r][c] == 0) {
                    System.out.printf(FSPACE, "");
                } else {
                    System.out.printf(FORMAT, M[r][c]);
                }
            }
            System.out.println();
        }
    }

}