Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
我在[LeetCode]–54. Spiral Matrix这篇博客中写了visitCircle的方法,其实跟这个大相径庭的,这个里面我写了fillCircle的方法。思想是一样的,也是一圈一圈的往里填。
public class Solution {
private static int index = 1;
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++)
if (matrix[i][i] == 0)
fillCircle(matrix, i, n);
return matrix;
}
public void fillCircle(int[][] a, int m, int n) {
for (int i = m; i < n - m; i++) {
a[m][i] = index++;
}
for (int i = 1 + m; i < n - m; i++) {
a[i][n - m - 1] = index++;
}
if (n - 2 * m == 1 || n - 2 * m == 1)
return;
for (int i = n - 2 - m; i >= m; i--) {
a[n - m - 1][i] = index++;
}
for (int i = n - m - 2; i > m; i--) {
a[i][m] = index++;
}
}
}
但是这个没有AC理由是输入2的时候答案是不正确的。但是我runCode的时候答案又是正确的,而且我在我eclipse里面完全正确啊。感觉是个bug吧。
再来个可以AC的算法。
public int[][] generateMatrix1(int n) {
if (n < 0) {
return null;
}
int[][] result = new int[n][n];
int xStart = 0;
int yStart = 0;
int num = 1;
while (n > 0) {
if (n == 1) {
result[yStart][xStart] = num++;
break;
}
for (int i = 0; i < n - 1; i++) {
result[yStart][xStart + i] = num++;
}
for (int i = 0; i < n - 1; i++) {
result[yStart + i][xStart + n - 1] = num++;
}
for (int i = 0; i < n - 1; i++) {
result[yStart + n - 1][xStart + n - 1 - i] = num++;
}
for (int i = 0; i < n - 1; i++) {
result[yStart + n - 1 - i][xStart] = num++;
}
xStart++;
yStart++;
n = n - 2;
}
return result;
}