題目
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]分析
和Spiral Matrix一樣的思路,但是矩陣是方陣了,代碼會更簡潔些。
代碼
public class SpiralMatrixII { public int[][] generateMatrix(int n) { int[][] matrix = new int[n][n]; int min = 0; int max = n - 1; int num = 1; while (min <= max) { for (int i = min; i <= max; ++i) { matrix[min][i] = num++; } for (int i = min + 1; i <= max; ++i) { matrix[i][max] = num++; } if (min != max) { for (int i = max - 1; i >= min; --i) { matrix[max][i] = num++; } } for (int i = max - 1; i > min; --i) { matrix[i][min] = num++; } ++min; ++max; } return matrix; } }