本文主要是介绍[LeetCode]54.Spiral Matrix,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
【题目】
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;}//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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!