首页 > 其他 > 详细

【LeetCode】Spiral Matrix II

时间:2014-12-11 15:31:23      阅读:306      评论:0      收藏:0      [点我收藏+]

Spiral Matrix II

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

 

Spiral Matrix实现基本一致,只不过上题是遍历输出,这题是遍历输入。

class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        //n by n matrix
        vector<vector<int> > matrix(n, vector<int>(n,0));
        if(n == 0)
            return matrix;
        int level = (n%2==0)?(n/2):(n/2+1);
        int number = 1;
        for(int i = 0; i < level; i ++)
        {
            //from up-left to up-right
            for(int j = i; j < n-i; j ++)
                matrix[i][j] = number++;
            //from up-right to down-right
            for(int j = i+1; j < n-i; j ++)
                matrix[j][n-1-i] = number++;
            //from down-right to down-left
            for(int j = n-1-i-1; j >= i; j --)
                matrix[n-1-i][j] = number++;
            //from down-left to up-left
            for(int j = n-1-i-1; j > i; j --)
                matrix[j][i] = number++;
        }
        return matrix;
    }
};

bubuko.com,布布扣

【LeetCode】Spiral Matrix II

原文:http://www.cnblogs.com/ganganloveu/p/4157415.html

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