[leetcode] 54. Spiral Matrix

网友投稿 232 2022-08-26

[leetcode] 54. Spiral Matrix

Description

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

Example 1:

Input:

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

Output:

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

Example 2:

Input:

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

Output:

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

分析

题目的意思是:螺旋输出m*n矩阵的值。

常规的矩阵遍历做法,其中要注意矩阵判空,然后遍历矩阵的时候要考虑矩阵的行和列只有一行的情况。

代码

class Solution {public: vector spiralOrder(vector>& matrix) { vector res; if(matrix.size()==0){ return res; } int rows=matrix.size()-1; int cols=matrix[0].size()-1; int row=0; int col=0; while(row<=rows&&col<=cols){ for(int i=col;i<=cols;i++){ res.push_back(matrix[row][i]); } row++; for(int i=row;i<=rows;i++){ res.push_back(matrix[i][cols]); } cols--; if(row<=rows){ for(int i=cols;i>=col;i--){ res.push_back(matrix[rows][i]); } } rows--; if(col<=cols){ for(int i=rows;i>=row;i--){ res.push_back(matrix[i][col]); } } col++; } return res; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:mac 用brew安装node.js 指定版本
下一篇:极狐一年营销费仅4亿,打破靠钱堆营销的格局!(极狐 销售)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~