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

【LeetCode】Spiral Matrix II

时间:2014-12-11 15:32:53      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   sp   for   strong   

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

标签:style   blog   http   io   ar   color   sp   for   strong   

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

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