您的位置:首页 > 其它

59. Spiral Matrix II

2016-12-01 10:11 232 查看
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 ]
]


public class Solution {
public int[][] generateMatrix(int n) {
int[][] a = new int

;
if(n == 0) return a;
if(n == 1) {
a[0][0] = 1;
return a;
}
int top = 0;
int bottom = n -1;
int left = 0;
int right = n - 1;
int num = 1;
while(top <= bottom && left <= right){
//right to left in top
for(int i = left ; i <= right ; i++){
a[top][i] = num;
num++;
}
top++;

//top to bottom in right
for(int i = top ; i <= bottom ; i++){
a[i][right] = num;
num++;
}
right--;

// right ->  left in bottom
if(bottom >= top){
for(int i = right ; i >= left ; i--){
a[bottom][i] = num;
num++;
}
bottom--;
}

//bottom -> top in left
if(right >= left){
for(int i = bottom ; i >= top ; i--){
a[i][left] = num;
num++;
}
left++;
}
}
return a;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: