LeetCode Spiral Matrix
来源:互联网 发布:手机电脑无线连接软件 编辑:程序博客网 时间:2024/05/29 12:13
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]
.
思路:将右,下,左,上连成环后,遍历,注意范围。
class Solution {public: vector<int> spiralOrder(vector<vector<int> > &matrix) { vector<int> ans; if (matrix.empty()) return ans; int n = matrix.size(), m = matrix[0].size(); int vis[1000][1000]; memset(vis, 0, sizeof(vis)); int dx[4] = {0, 1, 0, -1}; int dy[4] = {1, 0, -1, 0}; int dir = 0, x = 0, y = 0; for (int i = 0; i < n*m; i++) { ans.push_back(matrix[x][y]); vis[x][y] = 1; if (x+dx[dir] == n || x+dx[dir] < 0 || y+dy[dir] == m || y+dy[dir] < 0 || vis[x+dx[dir]][y+dy[dir]]) { dir = (dir == 3) ? 0 : dir+1; } x += dx[dir]; y += dy[dir]; } return ans; }};
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
- 关于大型网站技术演进的思考(一):存储的瓶颈(1)
- 使用AFNetworking, SDWebimage和OHHTTPStubs
- AFNetworking下载网络相关的附件(音视频)等到本地app包中做离线来提高用户体验
- 代码与结果的上传(运行情况截图)-test
- Java 连接Sql sever 2008
- LeetCode Spiral Matrix
- HTML5----响应式(自适应)网页设计
- 使用SES发邮件
- 别名显示规则
- Intellij idea使用java编写并执行spark程序
- HTTP协议与HTML表单(再谈GET与POST的区别)
- C++ 编写Windows服务
- goto对资源的释放问题的解决
- 调用手机的摄像头,并且返回照片显示在程序界面上.