[LeetCode] 59. Spiral Matrix II

55次阅读

共计 599 个字符,预计需要花费 2 分钟才能阅读完成。

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;
}
}

正文完
 0