欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

leetcode第十周解题总结

程序员文章站 2022-05-11 13:39:25
...

54. Spiral Matrix

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

题意解析:
对一个矩阵进行螺旋式的访问

解题思路:
将螺旋式的访问顺序变成四个部分进行操作。
leetcode第十周解题总结

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> result;
        int m = matrix.size();
        if (m == 0) return result;
        int n = matrix[0].size();


        int row = 0;
        int col = -1;
        while (true) {
            for(int i = 0; i < n; i ++) {
                col++;
                result.push_back(matrix[row][col]);
            }
            m--;
            if(m == 0) break;
            for(int i = 0; i < m; i ++) {
                row++;
                result.push_back(matrix[row][col]);
            }
            n--;
            if(n == 0) break;
            for(int i = 0; i < n; i ++) {
                col--;
                result.push_back(matrix[row][col]);
            }
            m--;
            if(m == 0) break;
            for(int i = 0; i < m; i ++) {
                row--;
                result.push_back(matrix[row][col]);
            }
            n--;
            if(n == 0) break;
        }
        return result;

    }
};