力扣 Hot 100 刷题记录 - 螺旋矩阵

力扣 Hot 100 刷题记录 - 螺旋矩阵

问题描述

题目链接:螺旋矩阵

题目难度:中等

题目描述:给定一个 m x n 的矩阵 matrix,按螺旋顺序返回矩阵中的所有元素。

示例 1

输入: matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出: [1,2,3,6,9,8,7,4,5]
解释: 按螺旋顺序遍历矩阵。

**示例 **:

输入: 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]
解释: 按螺旋顺序遍历矩阵。

解题思路

1. 模拟螺旋遍历

螺旋矩阵的遍历顺序是:从左到右、从上到下、从右到左、从下到上。我们需要模拟这个过程,逐步遍历矩阵的每一层。

实现步骤
模拟螺旋遍历

螺旋矩阵的遍历顺序是:从左到右、从上到下、从右到左、从下到上。我们需要模拟这个过程,逐步遍历矩阵的每一层。

  1. 初始化边界
    • 定义四个边界变量:topbottomleftright,分别表示当前螺旋层的上下左右边界。
    int top = 0, bottom = matrix.size() - 1;
    int left = 0, right = matrix[0].size() - 1;
    
  2. 模拟螺旋遍历
    按照从左到右、从上到下、从右到左、从下到上的顺序遍历矩阵的每一层。每次遍历完一层后,更新边界变量,缩小螺旋层的范围。
inwhile (top <= bottom && left <= right) {
 // 从左到右
 for (int i = left; i <= right; ++i) {
     result.push_back(matrix[top][i]);
 }
 top++;

 // 从上到下
 for (int i = top; i <= bottom; ++i) {
     result.push_back(matrix[i][right]);
 }
 right--;

 if (top <= bottom) {
     // 从右到左
     for (int i = right; i >= left; --i) {
         result.push_back(matrix[bottom][i]);
     }
     bottom--;
 }

 if (left <= right) {
     // 从下到上
     for (int i = bottom; i >= top; --i) {
         result.push_back(matrix[i][left]);
     }
     left++;
 }
}

代码

#include 
using namespace std;

vector<int> spiralOrder(vector<vector<int>>& matrix) {
  vector<int> result;
  if (matrix.empty()) return result;

  int top = 0, bottom = matrix.size() - 1;
  int left = 0, right = matrix[0].size() - 1;

  while (top <= bottom && left <= right) {
      // 从左到右
      for (int i = left; i <= right; ++i) {
          result.push_back(matrix[top][i]);
      }
      top++;

      // 从上到下
      for (int i = top; i <= bottom; ++i) {
          result.push_back(matrix[i][right]);
      }
      right--;

      if (top <= bottom) {
          // 从右到左
          for (int i = right; i >= left; --i) {
              result.push_back(matrix[bottom][i]);
          }
          bottom--;
      }

      if (left <= right) {
          // 从下到上
          for (int i = bottom; i >= top; --i) {
              result.push_back(matrix[i][left]);
          }
          left++;
      }
  }

  return result;
}

你可能感兴趣的:(leetcode,矩阵,算法)