美文网首页
54.螺旋矩阵

54.螺旋矩阵

作者: HITZGD | 来源:发表于2018-11-06 21:45 被阅读0次

题目
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]

示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
思路
横着搜索到头,然后竖着搜索

#include <vector>
using namespace std;
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> result;
        if (matrix.empty())
        {
            return result;
        }
        int x = 0, y = 0, x2 = matrix[0].size() - 1, y2 = matrix.size() - 1;
        while (x <= x2 && y <= y2)
        {
            for (int i = x; i <= x2; i++) result.push_back(matrix[y][i]);
            for (int j = y + 1; j <= y2; j++) result.push_back(matrix[j][x2]);
            if(x < x2 && y < y2)
            {
                for (int p = x2 - 1; p > x; p--) result.push_back(matrix[y2][p]);
                for (int q = y2 ; q >y; q--) result.push_back(matrix[q][x]);
            }

            x++; y++; x2--; y2--;
        }
        return result;
    }
};

int main(int argc, char* argv[])
{
    vector<vector<int>> matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9},{ 10, 11, 12 } };
    auto res = Solution().spiralOrder(matrix);
    return 0;
}

相关文章

网友评论

      本文标题:54.螺旋矩阵

      本文链接:https://www.haomeiwen.com/subject/zdupxqtx.html