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

问个简单的输出问题
int i=5;  
1 2 3 4 5  
16 17 18 19 6  
15 24 25 20 7  
14 23 22 21 8  
13 12 11 10 9  
  
int i=6  
1 2 3 4 5 6  
20 21 22 23 24 7  
19 32 33 34 25 8  
18 31 36 35 26 9  
17 30 29 28 27 10  
16 15 14 13 12 11  
(请问怎么用java输出这样图形...想了一个小时没什么思路大牛们解惑下...)

------解决方案--------------------
内螺旋矩阵算法分析
http://shuishou119800.iteye.com/blog/549592
------解决方案--------------------
Java code

public class Matrix {
    static void evaluateMatrix(int[][] matrix, int n){
        int i = 0, j, tline, trow;
        int line = 0, row = 0;        
        tline = n;
        trow = n;
        i = 0;
        // 赋值
        while (i < n * n - 1) {
            for (j = 0; j < trow - 1; ++j)
                matrix[line][row++] = i++;
            for (j = 0; j < tline - 1; ++j)
                matrix[line++][row] = i++;
            for (j = 0; j < trow - 1; ++j)
                matrix[line][row--] = i++;
            for (j = 0; j < tline - 1; ++j)
                matrix[line--][row] = i++;
            ++line;
            ++row;
            tline -= 2;
            trow -= 2;
        }
        if(n % 2 == 1)
            matrix[line][row] = i;
    }
    public static void main(String[] args) {        
        int n = 5;
        int[][] matrix = new int[n][n];
        evaluateMatrix(matrix, n);
        // 输出
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                System.out.print(matrix[i][j] + "  ");
            }
            System.out.println();
        }

    }
}