码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode Spiral Matrix II

时间:2014-11-05 23:06:02      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   使用   for   sp   

题目:是Spiral Matrix相关的的。这题的意思是给定一个n,那么在n*n的矩阵里按照循环记录将1,2,3,..., n*n。如下如果给定3,那么:

[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
一开始我想是不是有数学公式直接下标对应的,那直接遍历输出就可以了。但是推了一会,没有什么好的头绪。于是就分情况讨论了,和Spiral Matrix一样的分情况,只是这里的分情况是记录在数组里面。
利用上,下,左,右,分别记录每次循环可以到达的四个边界,我们每次就输出一环,走完一环往内走。
需要注意的:
1.要用下标访问vector<vector> >需要先声明大小才可以使用下标访问。
2.每走完一环,相应更新四个方向。
3.如果是奇数,那么n*n这个数需要另外存。也就是存在[n/2][n/2]的位置。
class Solution {
public:
vector<vector<int> > generateMatrix(int n)
{
    vector<int> sub(n);
    vector<vector<int> > ans(n, sub); // 也可以用vector<vector<int> > ans(n, vector<int>(n));
    if (n < 1) return ans;
    int val = 1, left = 0, right = n-1, up = 1, down = n-1;
    for (int i = 0; i < n/2; i++)
    {
        for (int j = left; j <= right; j++)
        {
            ans[i][j] = val++;
        }
        for (int j = up; j <= down; j++)
        {
            ans[j][right] = val++;
        }
        for (int j = right - 1; j>=left; j--)
        {
            ans[down][j] = val++;
        }
        for (int j = down - 1; j >= up; j--)
        {
            ans[j][left] = val++;
        }
        left++; right--; up++; down--;
    }
    if (n%2)
        ans[n/2][n/2] = n*n;
    return ans;
}
};

 

leetcode Spiral Matrix II

标签:style   blog   http   io   color   ar   使用   for   sp   

原文地址:http://www.cnblogs.com/higerzhang/p/4077509.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!