面试经典150题——Day35

文章目录

一、题目

54. Spiral Matrix

Given an m x n matrix, return all elements of the matrix in spiral order.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]

Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]

Output: [1,2,3,4,8,12,11,10,9,5,6,7]

Constraints:

m == matrix.length

n == matrix[i].length

1 <= m, n <= 10

-100 <= matrix[i][j] <= 100

二、题解

确定边界,进行模拟

cpp 复制代码
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        vector<int> res;
        //左边界,右边界,上边界,下边界
        int left = 0,right = n - 1,up = 0,down = m - 1;
        while(true){
            //从左到右
            for(int j = left;j <= right;j++) res.push_back(matrix[up][j]);
            //上边界下移
            if(++up > down) break;
            //从上到下
            for(int i = up;i <= down;i++) res.push_back(matrix[i][right]);
            //右边界左移
            if(--right < left) break;
            //从右到左
            for(int j = right;j >= left;j--) res.push_back(matrix[down][j]);
            //下边界上移
            if(--down < up) break;
            //从下到上
            for(int i = down;i >= up;i--) res.push_back(matrix[i][left]);
            //左边界右移
            if(++left > right) break;
        }
        return res;
    }
};
相关推荐
HUTAC几秒前
关于进制转换及其应用的算法题总结
数据结构·c++·算法
im_AMBER4 分钟前
Leetcode 144 位1的个数 | 只出现一次的数字
学习·算法·leetcode
暮冬-  Gentle°8 分钟前
C++中的工厂模式实战
开发语言·c++·算法
Lisssaa9 分钟前
打卡第二十二天
c++·算法·图论
pu_taoc10 分钟前
理解 lock_guard, unique_lock 与 shared_lock 的设计哲学与应用场景
开发语言·c++·算法
小刘不想改BUG13 分钟前
LeetCode 138.随机链表的复制 Java
java·leetcode·链表·hash table
XW010599921 分钟前
6-函数-1 使用函数求特殊a串数列和
数据结构·python·算法
myloveasuka28 分钟前
红黑树、红黑规则、添加节点处理方案
开发语言·算法
沉鱼.4429 分钟前
枚举问题集
java·数据结构·算法
2301_8101609529 分钟前
C++中的访问者模式高级应用
开发语言·c++·算法