leetcode Spiral Matrix
来源:互联网 发布:js怎么改变css样式 编辑:程序博客网 时间:2024/04/30 03:56
此题并不需要利用复杂的数据结构,但需要将问题分解
顺时针遍历二维数组,把二维数组看作由若干个顺时针方向的圈组成,分别对每一圈进行打印
注意到第一圈左上角坐标为(0,0),第二圈(1,1).。。。可将(start, start)作为每圈的起始位置
对5x5的矩阵来说,最后一圈只有一个数字,其位置为(2,2), 2*2<5, 依次列举发现规律,可将cols > 2*start && rows > 2*start 作为循环继续的条件
接下来考虑每一圈的情况,分为四部,从左到右, 从上到下,从右到左,从下到上
不过值得注意的是,最后一圈可能退化成只有一行,只有一列等情况,因此打印每一步时需要进行判断
剑指offer中有详细介绍,如下
代码
class Solution {public: vector<int> spiralOrder(vector<vector<int> > &matrix) { vector<int> result; int rows = matrix.size(); if(rows<=0) return result; int cols = matrix[0].size(); if(cols<=0) return result; int start = 0; while(cols>start*2&&rows>start*2) { spiralorderHelper(matrix, rows, cols, start, result); start++; } return result; } void spiralorderHelper(vector<vector<int> > &matrix, int rows, int cols, int start, vector<int> &result) { int endX = rows - start - 1; int endY = cols - start - 1; //from left to right for(int i = start; i <= endY; ++i) { result.push_back(matrix[start][i]); } //from top to bottom if(start < endX) { for(int j = start+1; j <= endX; ++j) { result.push_back(matrix[j][endY]); } } //from right to left if(start < endX && start < endY) { for(int i = endY-1; i >= start; --i) result.push_back(matrix[endX][i]); } //from bottom to top if(start < endY && start < endX-1) { for(int j = endX-1; j > start; --j) result.push_back(matrix[j][start]); } }};
0 0
- [leetcode]Spiral Matrix&&Spiral Matrix II
- Leetcode:Spiral Matrix与Spiral Matrix II
- LeetCode | Spiral Matrix /Spiral Matrix II
- 【Leetcode】【python】Spiral Matrix/Spiral Matrix II
- LeetCode: Spiral Matrix
- LeetCode: Spiral Matrix II
- LeetCode Spiral Matrix
- LeetCode Spiral Matrix II
- [Leetcode] Spiral Matrix
- [Leetcode] Spiral Matrix II
- LeetCode: Spiral Matrix
- LeetCode : Spiral Matrix II
- [LeetCode] Spiral Matrix II
- [LeetCode] Spiral Matrix
- leetcode 80: Spiral Matrix
- [Leetcode] Spiral Matrix
- [LeetCode]Spiral Matrix
- [LeetCode]Spiral Matrix II
- UVALive - 3635 Pie
- HDU 1536 && POJ 2960 S-Nim SG函数
- 图形学入门典藏
- Qt操作Excel文件
- stm8s 串行通信发送正常,无法接收
- leetcode Spiral Matrix
- Red5学习笔记(一)Red5应用创建与发布
- linux驱动中分配连续物理内存
- HDU 2126 - Buy the souvenirs(01背包)
- python open读写函数
- 读《影响力》总结
- 链接重定位和装载重定位
- c/c++ ctags cscope
- [0001] CentOS7下部署nginx+mongrel+rails环境