[LeetCode] Spiral Matrix

来源:互联网 发布:批处理编程 编辑:程序博客网 时间:2024/06/06 19:04

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].

问题描述:给定一个m*n的矩阵,以旋转顺序返回这个矩阵的所有元素。

这道题跟Spiral Matrix II类似,只是那道题要生成这个矩阵,而且是个方阵。

class Solution {public:vector<int> spiralOrder(vector<vector<int> > &matrix){vector<int> result;if(matrix.size() == 0) {return result;}int startx = 0, endx = matrix[0].size() - 1;int starty = 0, endy = matrix.size() - 1;int i = 0;while(true) {for(i = startx; i <= endx; ++i) {result.push_back(matrix[starty][i]);}if(++starty > endy) {break;}for(i = starty; i <= endy; ++i) {result.push_back(matrix[i][endx]);}if(--endx < startx) {break;}for(i = endx; i >= startx; --i) {result.push_back(matrix[endy][i]);}if(--endy < starty) {break;}for(i = endy; i >= starty; --i) {result.push_back(matrix[i][startx]);}if(++startx > endx) {break;}}return result;}};



0 0