Leetcode 54. Spiral Matrix
来源:互联网 发布:怎么从淘宝搜片 编辑:程序博客网 时间:2024/06/17 05:35
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].
s思路:
1. 又是一道比较nasty的题,看起来繁琐得很。但仔细思考发现还是有趣味,重复那句话:没有无聊的题,只有无聊的解答过程。如何把规则转换成编程或数学语言:首先,对坐标[x,y],遍历顺序是:y++到右边界;x++到下边界;y–到左边界;x–到上边界,依此法循环往复。这里,有意思的是,上下左右边界并不是固定不变,而是随着遍历发生加一或减一,例如:当y++到右边界时,此时就要把上边界加一,因为这一行都访问完,再不用。最后怎么结束呢?就是当左边界>右边界&&上边界>下边界,即:边界内没有数了!
class Solution {public: vector<int> spiralOrder(vector<vector<int>>& matrix) { // int m=matrix.size(); if(m==0) return {}; int n=matrix[0].size(); if(m<=1) return matrix[0]; vector<int> res; int l=0,r=n-1; int u=0,d=m-1; while(l<=r&&u<=d){ int x,y; for(y=l;y<=r;y++)//从左往右 res.push_back(matrix[u][y]);//取上边界值 u++; for(x=u;x<=d;x++)//从上往下 res.push_back(matrix[x][r]);//取右边界值 r--; for(y=r;y>=l&&u<=d;y--)//从右往左 res.push_back(matrix[d][y]);//取下边界值 d--; for(x=d;x>=u&&l<=r;x--)//从下往上 res.push_back(matrix[x][l]);//取左边界值 l++; } return res; }};
0 0
- LeetCode 54. Spiral Matrix
- [LeetCode]54.Spiral Matrix
- LeetCode --- 54. Spiral Matrix
- [Leetcode] 54. Spiral Matrix
- [leetcode] 54.Spiral Matrix
- Leetcode-54.Spiral Matrix
- **LeetCode 54. Spiral Matrix
- Leetcode 54. Spiral Matrix
- [leetcode] 54. Spiral Matrix
- leetcode 54. Spiral Matrix
- 54. Spiral Matrix LeetCode
- leetcode 54. Spiral Matrix
- LeetCode *** 54. Spiral Matrix
- [LeetCode]54. Spiral Matrix
- LeetCode 54. Spiral Matrix
- LeetCode--54. Spiral Matrix
- LeetCode - 54. Spiral Matrix
- [Leetcode]54. Spiral Matrix
- IntelliJ IDEA License Server本地搭建教程
- sscanf函数用法详解
- android-excel操作
- 【小云工作室】我的第一个开源项目
- JS操作数组的方法
- Leetcode 54. Spiral Matrix
- 二叉树简历 先序遍历
- 【开源.NET】 分享一个前后端分离的轻量级内容管理框架
- P1001 A+B Problem
- Leetcode 55. Jump Game
- PAT1004. 成绩排名 (20)
- label for id
- jquery学习(四)事件处理
- 【算法整理】听说你写的算法很牛?-优质算法衡量标准探讨