Spiral Matrix

来源:互联网 发布:怎么做网络营销 知乎 编辑:程序博客网 时间:2024/06/18 16:25

一、问题描述

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个元素,所以只要外层循环中数组中元素小于等于总元素个数即可。内部有四个循环,分别是从左到右、从上到下、从右到左和从下到上,每进行完一个循环都要判断元素书否达到上限m*n,执行完4个循环后需要将i加一。

三、代码

class Solution {public:    vector<int> spiralOrder(vector<vector<int>>& matrix) {        vector<int> vec;        if (matrix.empty()) return {};        int m = matrix.size();        int n = matrix[0].size();        int i = 0, sum = m * n,x,y;        while(vec.size() <= sum){            x = i;            for(y = i; y < n -i; ++y)                vec.push_back(matrix[x][y]);            if(vec.size() == sum) break;                        y = n - i - 1;            for(x = i + 1; x < m - i; ++x)                vec.push_back(matrix[x][y]);            if(vec.size() == sum) break;                        x = m - 1 - i;            for(y = n - 2 - i; y >= i; --y)                vec.push_back(matrix[x][y]);            if(vec.size() == sum) break;                        y = i;            for(x = m - 2 - i; x > i;--x)                vec.push_back(matrix[x][y]);            if(vec.size() == sum) break;                        ++i;        }        return vec;    }};


0 0
原创粉丝点击