Problem
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3Output:[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
Solution
class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
if (n == 0) return res;
int num = 1, rStart = 0, rEnd = n-1, cStart = 0, cEnd = n-1;
while (rStart <= rEnd && cStart <= cEnd) {
for (int j = cStart; j <= cEnd; j++) res[rStart][j] = num++;
rStart++;
for (int i = rStart; i <= rEnd; i++) res[i][cEnd] = num++;
cEnd–;
for (int j = cEnd; j >= cStart; j–) {
if (rStart > rEnd) break;
res[rEnd][j] = num++;
}
rEnd–;
for (int i = rEnd; i >= rStart; i–) {
if (cStart > cEnd) break;
res[i][cStart] = num++;
}
cStart++;
}
return res;
}
}
[LeetCode] 59. Spiral Matrix II
作者:
在
发表回复