[LeetCode]Spiral Matrix
2015-11-22 23:13
351 查看
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:
You should return
[思路]手动模拟循环输出过程。
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) { vector<int> ret; if(matrix.size()==0) return ret; int colmin = 0; int colmax = matrix.size()-1; int rowmin = 0; int rowmax = matrix[0].size()-1; int i=0; int j=0; int flag = 0; //走路顺序 while(rowmin<=rowmax&&colmin<=colmax){ if(flag==0){ for(j=rowmin; j<=rowmax; ++j) ret.push_back(matrix[i][j]); j = rowmax; //漏掉这个会出错,因为j会走到rowmax+1 ++colmin; flag = 1; continue; } if(flag == 1){ for(i=colmin; i<=colmax; ++i) ret.push_back(matrix[i][j]); i = colmax; --rowmax; flag = 2; continue; } if(flag == 2){ for(j=rowmax; j>=rowmin;--j) ret.push_back(matrix[i][j]); j = rowmin; --colmax; flag = 3; continue; } if(flag == 3){ for(i=colmax ; i>=colmin; --i) ret.push_back(matrix[i][j]); i = colmin; ++rowmin; flag = 0; continue; } } return ret; } };
相关文章推荐
- Android display架构分析
- 团队任务第一阶段
- angularjs的简单应用(一)
- JDK自带方法实现AES对称加密
- TCPIP、Http、Socket的区别
- iOS 将NSArray、NSDictionary转换为JSON格式进行网络传输
- Spring MVC的启动过程
- SVN使用教程
- nodejs连接MySQL,做简单的CRUD
- Android对话框详解
- 素数打表
- SAX解析XML文件
- MongoDB——运维技术
- 20135328陈都信息安全系统设计基础第十二周学习总结
- redis单实例、多实例、主从同步实战
- JavaScript学习之路09_闭包
- RelativeLayout子控件的一些属性
- 1005-行列式
- AfxBeginThread和CreateThread具体区别
- javascript_DOM 编程艺术学习笔记(七)