日期:2014-05-20 浏览次数:20698 次
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(); } } }