54. 螺旋矩阵

    科技2022-08-30  101

    给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

    示例 1:

    输入: [  [ 1, 2, 3 ],  [ 4, 5, 6 ],  [ 7, 8, 9 ] ] 输出: [1,2,3,6,9,8,7,4,5] 示例 2:

    输入: [   [1, 2, 3, 4],   [5, 6, 7, 8],   [9,10,11,12] ] 输出: [1,2,3,4,8,12,11,10,9,5,6,7]

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/spiral-matrix

    思路:顺时针模拟,

    注意红色和绿色遍历需要满足:left<=right,top<=bottom

    黄色和蓝色遍历需要满足:left<right,top<bottom

    class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> res; if(matrix.size()==0) return res; int n=matrix.size(),m=matrix[0].size(); for(int i=0;i<=n/2&&i<=m-1-i&&i<=n-1-i;i++)//left<=right,top<=bottom { for(int j=i;j<m-i;j++) { res.push_back(matrix[i][j]); // cout<<"a"; } for(int k=i+1;k<n-i;k++) { res.push_back(matrix[k][m-i-1]); // cout<<"b"; } if(n-1-i>i&&m-1-i>i)//left<right,top<bottom { for(int t=m-i-2;t>=i;t--) { res.push_back(matrix[n-1-i][t]); // cout<<"c"; } for(int z=n-i-2;z>i;z--) { res.push_back(matrix[z][i]); // cout<<"d"; } } } return res; } };

     

    Processed: 0.015, SQL: 9