Spiral Matrix II

来源:互联网 发布:淘宝api下载 编辑:程序博客网 时间:2024/05/16 19:13
-----QUESTION-----

Given an integer n,generate a square matrix filled with elements from 1to 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> > 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;};


0 0
原创粉丝点击