Spiral Matrix

来源:互联网 发布:谷歌笔试算法题 编辑:程序博客网 时间:2024/05/25 13:33

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


class Solution {public:    vector<int> spiralOrder(vector<vector<int> > &matrix) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int r_start = 0;        int c_start = 0;        int r_end = matrix.size();        int c_end = 0;        if (!matrix.empty()) {          c_end = matrix[0].size();        }        vector<int> result;        while (r_start < r_end && c_start < c_end) {             //保证for和++r_start一致性, row边界无变化,不用检查            if (c_start < c_end) {              for (int i = c_start; i < c_end; ++i) {                result.push_back(matrix[r_start][i]);              }              ++r_start;            }                        //保证for和--c_end一致性, comn边界无变化,不用检查            if (r_start < r_end) {                for (int i = r_start; i < r_end; ++i) {                  result.push_back(matrix[i][c_end -1]);              }              --c_end;            }                        //保证for和--r_end一致性, 且边界均有变化            if (r_start < r_end && c_start < c_end) {              for (int i = c_end - 1; i >= c_start; --i) {                  result.push_back(matrix[r_end - 1][i]);              }              --r_end;            }                        //保证for和++c_start一致性, 且边界均有变化            if (r_start < r_end && c_start < c_end) {              for (int i = r_end - 1; i >= r_start; --i) {                 result.push_back(matrix[i][c_start]);              }              ++c_start;            }        }        return result;    }};