Spiral Matrix

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

Given a matrix of m n elements(m rows, n columns),return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]

You should return [1,2,3,6,9,8,7,4,5].

-----SOLUTION-----

class Solution {public:    vector<int> spiralOrder(vector<vector<int>> &matrix) {        result.clear();        if(matrix.empty()) return result;                leftPos = 0;         rightPos = matrix[0].size()-1;         topPos = 0;         bottomPos = matrix.size()-1;        goWider(matrix, true);        return result;    }    void goWider(vector<vector<int>> &matrix, bool direct)    {        if(direct)        {            for(int i = leftPos; i<= rightPos; i++)            {                result.push_back(matrix[topPos][i]);            }            topPos++;            if(topPos > bottomPos) return;            goDeeper(matrix, true);        }        else        {            for(int i = rightPos; i>= leftPos; i--)            {                result.push_back(matrix[bottomPos][i]);            }            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++)            {                result.push_back(matrix[i][rightPos]);            }            rightPos--;            if(leftPos > rightPos) return;            goWider(matrix, false);        }        else        {            for(int i = bottomPos; i>= topPos; i--)            {                result.push_back(matrix[i][leftPos]);            }            leftPos++;            if(leftPos > rightPos) return;            goWider(matrix, true);        }    }private:    vector<int> result;    int leftPos;    int rightPos;    int topPos;    int bottomPos;};


0 0
原创粉丝点击