54. 螺旋矩阵

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 1:

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

示例 2:

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

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

转向数组

根据已知结果集中存储数据个数进行循环遍历。

1、首先,根据每次转弯的行列索引变化总结转向矩阵;
vector<vector<int>> turnVec{``{0,1},{1,0},{0,-1},{-1,0}};//向右、向下、向左、向上

2、其次,根据边界和是否访问过作为约束条件,控制转向;

3、最后,直至结果集元素个数达到上限,即遍历结束。

cpp 复制代码
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int rows = matrix.size();
        int cols = matrix[0].size();
        vector<int> ans;
        vector<vector<int>> turnVec{{0,1},{1,0},{0,-1},{-1,0}};//向右、向下、向左、向上
        int i = 0,j = 0;
        int turn = 0;
        int next_i,next_j;
        while(ans.size()<rows*cols){
            ans.push_back(matrix[i][j]);
            matrix[i][j] = 101;//指定矩阵中存储的最大元素值为100
            next_i = i + turnVec[turn % 4][0];//按照四个方向的顺序进行转弯
            next_j = j + turnVec[turn % 4][1];
            //判断是否需要转弯
            if(next_i>=rows||next_j>=cols||next_j<0||matrix[next_i][next_j]==101){
                ++turn;
                next_i = i + turnVec[turn % 4][0];
                next_j = j + turnVec[turn % 4][1];
            }
            i = next_i;
            j = next_j;
        }
        return ans;

    }
};
相关推荐
2301_803554526 分钟前
c++hpc岗位
c++
坐怀不乱杯魂9 分钟前
Linux - 线程
linux·c++
DuHz13 分钟前
UWB 雷达综述精读:应用、标准、信号处理、数据集、芯片与未来方向——论文阅读
论文阅读·学习·算法·信息与通信·信号处理
diediedei20 分钟前
C++中的适配器模式变体
开发语言·c++·算法
Timmylyx051824 分钟前
Codeforces Round 1075 (Div. 2) 题解
算法·codeforces·比赛日记
June bug29 分钟前
(#数组/链表操作)最长上升子序列的长度
数据结构·程序人生·leetcode·链表·面试·职场和发展·跳槽
hadage23332 分钟前
--- 力扣oj柱状图中最大的矩形 单调栈 ---
算法·leetcode·职场和发展
json{shen:"jing"}32 分钟前
18. 四数之和
数据结构·算法·leetcode
千逐-沐风33 分钟前
SMU-ACM2026冬训周报1st
算法
天赐学c语言33 分钟前
1.25 - 零钱兑换 && 理解右值以及move的作用
c++·算法·leecode