首页 > 其他 > 详细

Leetcode Spiral Matrix II

时间:2014-06-26 15:55:42      阅读:298      评论:0      收藏:0      [点我收藏+]

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

class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        vector<vector<int> > res(n,vector<int>(n,0));
        int dx[] = {0,1,0,-1};
        int dy[] = {1,0,-1,0};
        int cnt = 1,step = 0,x = 0 , y = 0;
        while(cnt <= n*n){
            step%=4;
            res[x][y] = cnt++;
            if(x+dx[step] >=n || x+dx[step] < 0 || y+dy[step] >=n || y+dy[step] < 0 || res[x+dx[step]][y+dy[step]]) step++;
            x+=dx[step%4];y+=dy[step%4];
        }
        return res;
    }
};

 

Leetcode Spiral Matrix II,布布扣,bubuko.com

Leetcode Spiral Matrix II

原文:http://www.cnblogs.com/xiongqiangcs/p/3809013.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!