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]
.
无
/**------------------------------------ * 日期:2015-02-05 * 作者:SJF0115 * 题目: 54.Spiral Matrix * 网址:https://oj.leetcode.com/problems/spiral-matrix/ * 结果:AC * 来源:LeetCode * 博客: ---------------------------------------**/ #include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: vector<int> spiralOrder(vector<vector<int> > &matrix) { vector<int> result; if(matrix.empty()){ return result; }//if int row = matrix.size(); int col = matrix[0].size(); int count = row * col; int index = 1; int beginX = 0,endX = row - 1; int beginY = 0,endY = col - 1; while(index <= count){ // right for(int i = beginY;i <= endY;++i){ result.push_back(matrix[beginX][i]); ++index; }//for ++beginX; if(beginX > endX){ break; }//if // down for(int i = beginX;i <= endX;++i){ result.push_back(matrix[i][endY]); ++index; }//for --endY; if(endY < beginY){ break; }//if // left for(int i = endY;i >= beginY;--i){ result.push_back(matrix[endX][i]); ++index; }//for --endX; if(endX < beginX){ break; }//if // up for(int i = endX;i >= beginX;--i){ result.push_back(matrix[i][beginY]); ++index; } ++beginY; if(beginX > endY){ break; }//if }//while return result; } }; int main(){ Solution s; vector<vector<int> > matrix = {{1,2,3},{4,5,6},{7,8,9}}; vector<int> result = s.spiralOrder(matrix); // 输出 for(int i = 0;i < result.size();++i){ cout<<result[i]<<" "; }//for cout<<endl; return 0; }
原文地址:http://blog.csdn.net/sunnyyoona/article/details/43525181