54-Spiral Matrix

来源:互联网 发布:java关键字有多少个 编辑:程序博客网 时间:2024/05/21 04:20
题目

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

分析

顺时针、螺旋输出二维矩阵。 这道题是参考的得票最高的Solution。
思路清晰,非常值得学习!!!

比较重要的四个变量rowBegin,rowEnd,colBegin,colEnd

每输出一行数据,更新一下rowBegin 或者rowEnd

每输出一列数据,更新一下colBegin或者colEnd

实现
/*Author: FancyDate:2017-03-15Algorithm:54-SpiralMatrixTime Complexity: O(m*n)*/class Solution {public:    vector<int> spiralOrder(vector<vector<int>>& matrix) {        vector<int> result;        if (matrix.empty() || matrix.size() == 0 || matrix[0].size() == 0)            return result;        int rows = matrix.size(), cols = matrix[0].size();        //保存起始位置        int rowBegin = 0, colBegin = 0;        int rowEnd = rows - 1, colEnd = cols - 1;        while (rowBegin <= rowEnd&&colBegin <= colEnd)        {            for (int i = colBegin; i <= colEnd; i++)                result.push_back(matrix[rowBegin][i]);            rowBegin++;            for (int i = rowBegin; i <= rowEnd; i++)                result.push_back(matrix[i][colEnd]);            colEnd--;            if(rowBegin<= rowEnd)                for (int i = colEnd; i >= colBegin; i--)                    result.push_back(matrix[rowEnd][i]);            rowEnd--;            if(colBegin<=colEnd)                for (int i = rowEnd; i >= rowBegin; i--)                    result.push_back(matrix[i][colBegin]);            colBegin++;        }        return result;    }};