Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n =
You should return the following matrix:Given n =
3,[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]Solution: 按照上右下左的顺序放,这道题是直接给出1到n^2, 每个元素只访问一次,时间复杂度是O(n^2), space complexity is O(n^2)。
public class Solution {
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
if(n == 0)
return result;
int top = 0, bottom = n - 1;
int left = 0, right = n - 1;
int k = 1;
while(top < bottom && left < right) {
for(int i = left; i < right; i++) {
result[top][i] = k++;
}
for(int i = top; i < bottom; i++) {
result[i][right] = k++;
}
for(int i = right; i > left; i--) {
result[bottom][i] = k++;
}
for(int i = bottom; i > top; i--) {
result[i][left] = k++;
}
top++;
bottom--;
left++;
right--;
}
if(n % 2 != 0) { //如果是奇数行,中心点要单独加
result[n / 2][n / 2] = k;
}
return result;
}
}
No comments:
Post a Comment