螺旋矩阵
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
思路: 主要设置了4个边界, 分别是上、下、左、右四个边界。
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { //if() vector<int> result; if(matrix.empty()) return result; int i1 = 0; int i2 = matrix.size()-1; int j1 = 0; int j2 = matrix[0].size()-1; while(true){ //从左到右 for(int n = j1; n<=j2; n++){ result.push_back(matrix[i1][n]); } //if(result.size() == matrix.size()*matrix[0].size()) break; if(++i1 > i2 ) break; //从上到下 for(int i = i1;i<=i2;i++){ result.push_back(matrix[i][j2]); } //if(result.size() == matrix.size()*matrix[0].size()) break; //j2--; if(--j2 < j1) break; //从右到左 for(int j = j2;j>=j1;j--){ result.push_back(matrix[i2][j]); } //if(result.size() == matrix.size()*matrix[0].size()) break; if(--i2 <i1) break; //从下到上 for(int k = i2; k >= i1; k--){ result.push_back(matrix[k][j1]); } //if(result.size() == matrix.size()*matrix[0].size()) break; if(++j1 > j2) break; //j1++; } for(int i = 0; i < result.size(); i++){ cout << result[i] << ","; } return result; } };
The Safest Way to Get what you Want is to Try and Deserve What you Want.