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 ]
]
一刷
題解:
跟Spiral Matrix I一樣娩梨,擁有top, bottom, left, right四個(gè)指針以及一個(gè)計(jì)數(shù)器斥季。
Time Complexity - O(n * n), Space Complexity - O(1)验毡。
public class Solution {
public int[][] generateMatrix(int n) {
int left=0, right = n-1, top = 0, bottom = n-1;
int[][] res = new int[n][n];
if(n==0) return res;
int total = n*n, count=1;
while(count<=total){
for(int i=left; i<=right; i++){
res[top][i] = count;
count++;
}
top++;
if(count<=total){
for(int i=top; i<=bottom; i++){
res[i][right] = count;
count++;
}
right--;
}
if(count<=total){
for(int i=right; i>=left; i--){
res[bottom][i] = count;
count++;
}
bottom--;
}
if(count<=total){
for(int i=bottom; i>=top; i--){
res[i][left] = count;
count++;
}
left++;
}
}
return res;
}
}