59. Spiral Matrix II (Array)

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;
};

 思路II:向右向下向左向上,4个for循环。外套一个while,while的结束条件是4个for循环都不满足循环条件了。

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int len = n;
        int num = 1;
        vector<vector<int>> ret(n, vector<int>(n,0));
        while(len>n-len){
            for(int i = n-len; i < len; i++){
                ret[n-len][i] = num++;
            }
            for(int j = n-len+1; j < len; j++){
                ret[j][len-1] = num++;
            }
            for(int k = len-2; k >= n-len; k--){
                ret[len-1][k] = num++;
            }
            for(int l = len-2; l > n-len; l--){
                ret[l][n-len] = num++;
            }
            len--;
        }
        return ret;
    }
};

 

posted on 2015-10-04 15:59  joannae  阅读(134)  评论(0编辑  收藏  举报

导航