小生想实现打印蛇形矩阵。请各位高手给个思路?1  3  4 10
2  5  9 11
6  8 12 15
7 13 14 16在这先言谢谢啦!

解决方案 »

  1.   


    public static void main(String[] args) {
            int n = 5; //邊長
            int dn = n - 1;
            int[][] val = new int[n][n];
            for (int i = 0; i < n; i++) {
                val[i] = new int[n];
            }
            int ct = 1;
            boolean xTOy = true;
            int x = 0;
            int y = 0;
            for (int i = -dn; i <= dn; i++) {
                for (int j = dn - Math.abs(i); j >= 0; j--) {
                    val[y][x] = ct;
                    if (j > 0) {
                        if (xTOy) {
                            x--;
                            y++;
                        } else {
                            y--;
                            x++;
                        }
                    }
                    ct++;
                }
                if (x == 0) {
                    if (y < dn) {
                        y++;
                    } else {
                        x++;
                    }
                } else if (y == 0) {
                    if (x < dn) {
                        x++;
                    } else {
                        y++;
                    }
                } else if (y == dn) {
                    x++;
                } else if (x == dn) {
                    y++;
                }
                if (xTOy) {
                    xTOy = false;
                } else {
                    xTOy = true;
                }
            }
            for (int i = 0; i < val.length; i++) {
                for (int j = 0; j < val[i].length; j++) {
                    System.out.print((val[i][j] > 9 ? " " : "  ") + val[i][j]);
                }
                System.out.println();
            }
        }
      

  2.   

    大概解釋一下
    因為是斜的增減,所以以斜邊為軸,但這樣沒辦法直接列印,所以先寫到陣列裡。
    以座標觀念來看
    從0,0 開始 碰到邊界 不是Y+1就是X+1
    然後每個下一點不是X-- Y++ 就是X++ Y--
    以這樣的觀念去修修改改就可以了。
      

  3.   

    我来贴一个,好像比1楼的短一点,不过自己依然不是很满意 int width = 6;
    int bits = 2;  //每个数的宽度,为了对齐美观
    String[] result = new String[width];
    for (int i=0; i<width; i++) result[i] = "";
    int current = 0;
    int direction = 1;
    int align ; //起始行
    for (int i=1; i<2*width; i++){
    int deep = width - Math.abs(i-width);
    if (i<=width)
    if (deep%2==1) align = 0;
    else align = deep - 1 ;
    else
    if (deep%2==0) align = width - 1;
    else align = width - deep;
    for (int j=1; j<=deep; j++){
    current++;
    result[align] += String.format("%"+bits+"d", current) + " ";
    align += direction;
    }
    direction *= -1;
    }
    for (String s : result) System.out.println(s);
      

  4.   

    LZ是不是想实现一个长度不定的蛇形矩阵呀,那还得传个参数n代表矩阵的长...