您的位置:首页 > 其它

59. Spiral Matrix II

2017-08-25 17:22 351 查看
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 startx = 0,starty = 0,endx = n-1,endy = n-1;
int[][] ans = new int

;
int count = 1;
while(startx <= endx && starty <= endy){
for(int i = startx;i<=endx;i++){
ans[starty][i] = count++;
}
starty++;

for(int i = starty;i<=endy;i++){
ans[i][endx] = count++;
}
endx--;

for(int i = endx;i>=startx;i--){
ans[endy][i] = count++;
}
endy--;

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