[LeetCode]54.Spiral Matrix

【题目】

Given a matrix ofmxnelements (mrows,ncolumns), 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;}//ifint 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){// rightfor(int i = beginY;i <= endY;++i){result.push_back(matrix[beginX][i]);++index;}//for++beginX;if(beginX > endX){break;}//if// downfor(int i = beginX;i <= endX;++i){result.push_back(matrix[i][endY]);++index;}//for–endY;if(endY < beginY){break;}//if// leftfor(int i = endY;i >= beginY;–i){result.push_back(matrix[endX][i]);++index;}//for–endX;if(endX < beginX){break;}//if// upfor(int i = endX;i >= beginX;–i){result.push_back(matrix[i][beginY]);++index;}++beginY;if(beginX > endY){break;}//if}//whilereturn 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]<<" ";}//forcout<<endl;return 0;}

,如果说对云南有进一步的了解的话就是鲜花。

[LeetCode]54.Spiral Matrix

相关文章:

你感兴趣的文章:

标签云: