leetcode54-Spiral Matrix(打印蛇形矩阵)

来源:互联网 发布:专业动漫制作软件 编辑:程序博客网 时间:2024/06/06 05:27

问题描述:

Given a matrix of m x 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].

问题求解:

class Solution {public:    vector<int> spiralOrder(vector<vector<int>>& matrix) {        //关键是要找到(x1,y1),(x2,y2)的位置,则上下左右的边界即可确定!!!        if(matrix.empty()) return {};        int m=matrix.size();        int n=matrix[0].size();        vector<int> res;        //(x1,y1)表示遍历每一圈左上角元素的位置(0,0),(1,1)...!!!        int x1=0, y1=0;        while(m>=1 && n>=1)        {//至少是1行1列,每遍历完一圈,m和n都减2            //(x2,y2)表示遍历每一圈右下角元素的位置(m-1,n-1),(m-2,n-2)...!!!            int x2=x1+m-1;            int y2=y1+n-1;            for(int i=y1;i<=y2;i++)            {//从左到右                res.push_back(matrix[x1][i]);            }            for(int i=x1+1;i<x2;i++)            {//从上到下(不包括上界和下界)                res.push_back(matrix[i][y2]);            }            if(m > 1)            {                for(int i=y2;i>=y1;i--)                {//从右到左                    res.push_back(matrix[x2][i]);                }            }            if(n > 1)            {                for(int i=x2-1;i>x1;i--)                {//从下到上(不包括上界和下界)                    res.push_back(matrix[i][y1]);                }            }            x1++;y1++;            m -= 2;            n -= 2;        }        return res;    }};
0 0
原创粉丝点击