首页 > 其他 > 详细

LeetCode: Spiral Matrix II [058]

时间:2014-05-25 07:07:44      阅读:364      评论: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 ]
]



【题意】

给定整数n, 将1,2,3...nxn个数按螺旋旋转的方式填入nxn的矩阵


【思路】

       

Spiral Matrix, 从外圈到内圈依次填写


【代码】

class Solution {
public:
    void generate(vector<vector<int> >&matrix, int i, int j, int len, int num){
        //i, j  当前圈左上角的坐标
        //len   当前圈的边长
        //num   将填入当前圈的第一个数值
        if(len<1)return;
        if(len==1){
            matrix[i][j]=num;
            return;
        }
        //填写上面的边
        int x=i, y=j;
        while(y<j+len-1){
            matrix[x][y++]=num++;
        }
        //填写后面的边
        while(x<i+len-1){
            matrix[x++][y]=num++;
        }
        //填写下面的边
        while(y>j){
            matrix[x][y--]=num++;
        }
        //填写左面的边
        while(x>i){
            matrix[x--][y]=num++;
        }
        //填写内圈
        generate(matrix, i+1, j+1, len-2, num);
    }
    vector<vector<int> > generateMatrix(int n) {
        vector<vector<int> >result(n, vector<int>(n, 0));
        generate(result, 0, 0, n, 1);
        return result;
    }
};


LeetCode: Spiral Matrix II [058],布布扣,bubuko.com

LeetCode: Spiral Matrix II [058]

原文:http://blog.csdn.net/harryhuang1990/article/details/26814291

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