Spiral Matrix
2016-02-28 22:43
323 查看
题目:
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
cpp:
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].
cpp:
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> result; if (matrix.empty()) return result; int m = matrix.size(); int n = matrix[0].size(); result.reserve(m * n); int r = 0; int c = 0; int i; while (r < m / 2 && c < n / 2) { //left to right for (i = c; i < n - c; i++) { result.push_back(matrix[r][i]); } //up to down for (i = r + 1; i < m - r; i++) { result.push_back(matrix[i][n - c - 1]); } //right to left for (i = n - c - 2; i >= c; i--) { result.push_back(matrix[m - c - 1][i]); } //down to up for (i = m - r - 2; i > r; i--) { result.push_back(matrix[i][r]); } r++; c++; } if (m >= n && 2*c < n) { for (i = r; i < m - r; i++) { result.push_back(matrix[i][c]); } } if(m<n && 2*r < m){ for (i = c; i < n - c; i++) { result.push_back(matrix[r][i]); } } return result; } };
相关文章推荐
- 10. Regular Expression Matching-hard
- Password Validation using regular expressions(JavaScript)
- 数据包解析(基于wireshark)——物理层Frame
- PL/SQL之函数处理
- 字符集和编码
- 【CodeForces 520E】Pluses everywhere
- Java的Calendar使用
- VM虚拟机centos中的网络站点、主机访问
- java.lang.NoSuchFieldError: android.support.v7.appcompat.R$styleable.Theme_w的解决办法
- hdu 1063 Exponentiation/poj 1001
- FFmpeg获取视频的旋转角度rotate函数,一定能获取!(要放在解析视频流的时候才能获取)
- JavaScript 定义类或对象
- HDU 1596 也是最小路径Dijkstra
- 3-8-循环队列-栈和队列-第3章-《数据结构》课本源码-严蔚敏吴伟民版
- web前端排版
- GitHub教程
- android第三方登录数据库设计以及业务数据流向说明
- 静态数据的初始化
- Java冒泡排序和二分查找(预习)
- Java常见日期格式及日期的计算工具类