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 =
You should return the following matrix:
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;
}
}
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;
}
}
相关文章推荐
- LeetCode-59-Spiral Matrix II(Array)-Medium
- 【LeetCode】(59)Spiral Matrix II(Medium)
- LeetCode --- 59. Spiral Matrix II
- LeetCode.54(59) Spiral Matrix && II
- LeetCode59 Spiral Matrix II
- 59. Spiral Matrix II
- leetcode59-Spiral Matrix II(生成蛇形矩阵)
- Middle-题目29:59. Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- LeetCode54/59 Spiral Matrix I/II
- 【LeetCode】59. Spiral Matrix II
- leetcode59 Spiral Matrix II
- 【leetcode】【59】Spiral Matrix II
- leetcode 59. Spiral Matrix II
- 59. Spiral Matrix II
- LeetCode 59 Spiral Matrix II(螺旋矩阵II)(Array)
- 59. Spiral Matrix II
- LeetCode_59---Spiral Matrix II
- LeetCode 59 Spiral Matrix II
- 59 Spiral Matrix II