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

LeetCode--Spiral Matrix II

时间:2015-01-12 14:42:40      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:leetcode   array   matrix   

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

class Solution 
{
public:
    vector<vector<int> > generateMatrix(int n) 
    {
        vector<vector<int>> res;
        for(int i=0; i<n; i++)
        {
            vector<int> temp(n,0);
            res.push_back(temp);
        }
        bool left_up = true;
        bool left_down = false;
        bool right_up = false;
        bool right_down = false;
        int min_i = 0;
        int max_i = n-1;
        int min_j = 0;
        int max_j = n-1;
        int count = 1;
        while(min_i<=max_i && min_j<=max_j)
        {
            if(left_up == true)
            {
                for(int j = min_j; j<=max_j; j++)
                {
                    res[min_i][j] = count;
                    count++;
                }
                left_up = false;
                right_up = true;
                min_i = min_i+1;
            }
            else if(right_up == true)
            {
                for(int i=min_i; i<=max_i; i++)
                {
                    res[i][max_j] = count;
                    count++;
                }
                max_j = max_j-1;
                right_up = false;
                right_down = true;
            }
            else if(right_down == true)
            {
                for(int j=max_j; j>=min_j; j--)
                {
                    res[max_i][j] = count;
                    count++;
                }
                max_i = max_i-1;
                left_down = true;
                right_down = false;
            }
            else
            {
                for(int i=max_i; i>=min_i; i--)
                {
                    res[i][min_j] = count;
                    count++;
                }
                min_j = min_j+1;
                left_up = true;
                left_down = false;
            }
        }
        return res;
    }
};



LeetCode--Spiral Matrix II

标签:leetcode   array   matrix   

原文地址:http://blog.csdn.net/shaya118/article/details/42641519

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