Leetcode:54. Spiral Matrix

Description

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example

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

思路

  • 剑指offer上的一个原题,反正就是自己控制吧,一圈一圈输出

代码

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> nums;
        int m = matrix.size();
        if(m == 0) return nums;
        int n = matrix[0].size();
        
        int start = 0;
        while(n > start * 2 && m > start * 2){
            print(nums, matrix, m, n, start);
            ++start;
        }
        
        return nums;
    }
    
    void print(vector<int>& nums, vector<vector<int>>& matrix, int m, int n, int start){
        int endM = m - 1 - start;
        int endN = n - 1 - start;
        
        //从左到右
        for(int i = start; i <= endN; ++i)
            nums.push_back(matrix[start][i]);
        
        //从上到下
        if(start < endM){
            for(int i = start + 1; i <= endM; ++i)
                nums.push_back(matrix[i][endN]);
        }
        
        //从右到左
        if(start < endM && start < endN){
            for(int i = endN - 1; i >= start; --i)
                nums.push_back(matrix[endM][i]);
        }
        
        if(start < endN && start < endM - 1){
            for(int i = endM - 1; i >= start + 1; --i)
                nums.push_back(matrix[i][start]);
        }
    }
};
原文地址:https://www.cnblogs.com/lengender-12/p/6864139.html