您的位置:首页 > 其它

Medium 59题 Spiral Matrix II

2016-09-24 11:42 211 查看
Question:

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 ]
]

Solution:
看了discussion豁然开朗。。。。。

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

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