1  18  17 16 15 14
2  19  28 27 26 13 
3  20  29 30 25 12
4  21  22 23 24 11
5  6   7  8  9  10
用Java写这样的阵型。要求一个函数。 接受一个参数  比如接受的参数是30 则输出上列这些。。额、、 今天突发奇想。 自己却心有力而力不足。

解决方案 »

  1.   

    http://blog.csdn.net/wuyu0314/archive/2009/05/05/4152399.aspx有人做过的
      

  2.   

    那个blog上面的例子有点小问题
    改了下给楼主public class SpiralData {
    public int getValueInSpiralMatrix(int x, int y, int max) {
    if ((x >= 0) && (y >= 0) && (x == y)) {//第一象限对角线的情况,直接返回结果   
    return max - (2 * x + 1) * (2 * x + 1);
    }else if(Math.abs(x) >= Math.abs(y)){//x的绝对值大于y的绝对值的情况
    if(x <= 0){//x在二三象限时,计算出左边x那列中间的数值根据y进行调整
    return max - (((2 * Math.abs(x) + 1) * (2 * Math.abs(x) + 1) - (2 * Math.abs(x)) - (2 * Math.abs(x) + 1)/2) + y);
    }else{//x在一四象限时,计算出右边x那列中间的数值根据y进行调整
    return max - (((2 * Math.abs(x) + 1) * (2 * Math.abs(x) + 1) - 3 * (2 * Math.abs(x)) - (2 * Math.abs(x) + 1)/2) - y);
    }
    }else{//x的绝对值小于y的绝对值的情况
    if(y >= 0){//和上一种情况类似
    return max - (((2 * Math.abs(y) + 1) * (2 * Math.abs(y) + 1) - (2 * Math.abs(y) + 1)/2) + x);
    }else{
    return max - (((2 * Math.abs(y) + 1) * (2 * Math.abs(y) + 1) - 2 * (2 * Math.abs(y)) - (2 * Math.abs(y) + 1)/2) - x);
    }
    }
    }

    public void printRect(int max) {
    int low = -(int)Math.sqrt(max)/2-1;
    int high = (int)Math.sqrt(max)/2+1;
    for (int i = low; i <= high; i++) {
    for(int j = low; j <= high; j++)
    if (getValueInSpiralMatrix(i, j , max) < 0) {
    System.out.print("    ");
    } else {
    System.out.printf("%4d" ,getValueInSpiralMatrix(i, j, max)+1);
    }
    System.out.println();
    }
    } public static void main(String[] args) {
    SpiralData data = new SpiralData();
    data.printRect(36);
    }
    }
      

  3.   

    如果不考虑如 31 这类问题,下边这个可以满足楼主要求public class Test { public static void main(String[] args){
    printMatrix(30);
        }
        
    public static void printMatrix(int num){
    int row = (int)Math.sqrt(num);
    int col = num / row;
    while(row * col != num){
    row--;
    col = num / row;
    }
    innerPrintMatrix(row, col);
    }

    private static void innerPrintMatrix(int row, int col){
    int[][] map = new int[row][col];
    int[][] directer = {{1,0},{0,1},{-1,0},{0,-1}};
    int temp = 0;
    int x = -1, y = 0;
    for(int i = 1; i <= row * col; i++){
    x += directer[temp][0];
    y += directer[temp][1];
    if(x < 0 || y < 0 || x >= row || y >= col || map[x][y] > 0){
    x -= directer[temp][0];
    y -= directer[temp][1];
    temp = (temp + 1) % 4;
    x += directer[temp][0];
    y += directer[temp][1];
    }
    map[x][y] = i;
    }
    for (int i = 0; i < map.length; i++) {
    for (int j = 0; j < map[i].length; j++) {
    System.out.print(map[i][j] + "\t");
    }
    System.out.println();
    System.out.println();
    }
    }}