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

59. Spiral Matrix II (Graph)

时间:2015-10-04 17:03:59      阅读:106      评论: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> > result(n, vector<int>(n,0));
        leftPos = 0; 
        rightPos = n-1; 
        topPos = 0; 
        bottomPos = n-1;
        currentNum = 1;
        goWider(result,true);
        return result;
    }
    void goWider(vector<vector<int> > &matrix, bool direct)
    {
        if(direct)
        {
            for(int i = leftPos; i<= rightPos; i++)
            {
                matrix[topPos][i] = currentNum++;
            }
            topPos++;
            if(topPos > bottomPos) return;
            goDeeper(matrix, true);
        }
        else
        {
            for(int i = rightPos; i>= leftPos; i--)
            {
                matrix[bottomPos][i] = currentNum++;
            }
            bottomPos--;
            if(topPos > bottomPos) return;
            goDeeper(matrix, false);
        }
    }
    void goDeeper(vector<vector<int> > &matrix, bool direct)
    {
        if(direct)
        {
            for(int i = topPos; i<= bottomPos; i++)
            {
                matrix[i][rightPos]=currentNum++;
            }
            rightPos--;
            if(leftPos > rightPos) return;
            goWider(matrix, false);
        }
        else
        {
            for(int i = bottomPos; i>= topPos; i--)
            {
                matrix[i][leftPos] = currentNum++;
            }
            leftPos++;
            if(leftPos > rightPos) return;
            goWider(matrix, true);
        }
    }
private:
    int currentNum;
    int leftPos;
    int rightPos;
    int topPos;
    int bottomPos;
};

 

59. Spiral Matrix II (Graph)

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/4854647.html

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