您的位置:首页 > 其它

leetcode 81: Spiral Matrix II

2013-02-18 08:02 495 查看
Spiral Matrix IIMar
28 '12

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) {
// Start typing your Java solution below
// DO NOT write main() function
int[][] res = new int

;
if(n<1) return res;

int top=0, bottom=n-1, left=0, right=n-1;

int loop = (n+1)/2;

for(int i=0, seq=1; i<loop; i++) {

for(int j=left; j<=right; j++) {
res[top][j] = seq++;
}
top++;

if(top>bottom) return res;
for(int j=top; j<=bottom; j++) {
res[j][right] = seq++;
}
right--;

if(left>right) return res;
for(int j=right; j>=left; j--) {
res[bottom][j] = seq++;
}
bottom--;

if(top>bottom) return res;
for(int j=bottom; j>=top; j--) {
res[j][left] = seq++;
}
left++;
}

return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: