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;

    }
};
相关推荐
米粒125 分钟前
力扣算法刷题 Day 31 (贪心总结)
算法·leetcode·职场和发展
少许极端29 分钟前
算法奇妙屋(四十)-贪心算法学习之路7
java·学习·算法·贪心算法
AlenTech1 小时前
647. 回文子串 - 力扣(LeetCode)
算法·leetcode·职场和发展
py有趣1 小时前
力扣热门100题之合并两个有序链表
算法·leetcode·链表
8Qi81 小时前
LeetCode热题100--45.跳跃游戏 II
java·算法·leetcode·贪心算法·编程
米饭不加菜1 小时前
机器人导论-通过逆矩阵公式证明齐次变换矩阵的逆
线性代数·矩阵·机器人
foundbug9992 小时前
基于STM32的步进电机加减速程序设计(梯形加减速算法)
stm32·单片机·算法
东北甜妹2 小时前
MYSQL 总结
数据结构
CheerWWW2 小时前
C++学习笔记——this关键字、对象生命周期(栈作用域)、智能指针、复制与拷贝构造函数
c++·笔记·学习
lucky九年2 小时前
GO语言模拟C++封装,继承,多态
开发语言·c++·golang