leetcode 53: Spiral Matrix
2015-07-28 19:15
405 查看
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> res; if(matrix.empty()) return res; int m=matrix.size(); int n=matrix[0].size(); int time=0,start=0; while(time!=m*n) { for(int i=start;i<n-start;i++) { res.push_back(matrix[start][i]); time++; } for(int i=start+1;i<m-start;i++) { res.push_back(matrix[i][n-start-1]); time++; } //do next step only if the numbers are not in a horizontal line for(int i=n-start-2;i>=start&&m-start-1>start;i--) { res.push_back(matrix[m-start-1][i]); time++; } //do next step only if the numbers are not in a vertical line for(int i=m-start-2;i>start&&n-start-1>start;i--) { res.push_back(matrix[i][start]); time++; } start++; } return res; } };
Updated version, imagine you go from (0,0) and change direction every time you meet a wall or some element that is visited.
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> res; int m=matrix.size(); if(m==0) return res; int n=matrix[0].size(); vector<vector<bool> > visited(m,vector<bool>(n,0)); int i=0,j=0; int dir=0; int count=0; while(1) { res.push_back(matrix[i][j]); visited[i][j]=1; count++; if(count==m*n) break; if(dir==0) { if(j!=n-1&&visited[i][j+1]==0) j++; else { dir++; i++; } } else if(dir==1) { if(i!=m-1&&visited[i+1][j]==0) i++; else { dir++; j--; } } else if(dir==2) { if(j!=0&&visited[i][j-1]==0) j--; else { dir++; i--; } } else if(dir==3) { if(i!=0&&visited[i-1][j]==0) i--; else { dir=0; j++; } } } return res; } };
相关文章推荐
- CSS截取字符串,额外的文本显示以省略号
- hdu 5326 dfs
- Codeforces Gym100571A Cursed Query
- LeetCode题解——Swap Nodes in Pairs
- 项目笔记用到的链接
- java培训 2015-07-28
- 杭电1087
- 数据结构和算法学习笔记-1
- [BZOJ1622] [Usaco2008 Open]Word Power 名字的能量
- 蚂蚁的难题(三)
- Invert Binary Tree
- POJ 1573 Robot Motion
- AFNetworking框架_上传文件或图像server
- chrome 支付宝控件安装
- iOS 获取联系人,并调用系统地址簿UI
- 为什是@property不自动生成属性?
- linux jstat 命令监控gc情况
- Leetcode35 Search Insert Position
- Eclipse — 每次启动都会Error when loading the SDK
- linux操作中,使用sed卡死的问题