c++面试题(14)------顺时针打印矩阵

  • 操作系统:ubuntu22.04
  • IDE:Visual Studio Code
  • 编程语言:C++11

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个元素。

例如:

bash 复制代码
输入矩阵:
[
 [ 1,  2,  3 ],
 [ 4,  5,  6 ],
 [ 7,  8,  9 ]
]

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

解法思路:模拟边界遍历(按圈打印)

这是一个非常经典的二维数组模拟题。

🧠 思路总结:

我们可以把矩阵想象成一圈一圈的"洋葱",从最外层开始,顺时针打印每一圈的四条边:

  • 从左到右 打印上边;
  • 从上到下 打印右边;
  • 从右到左 打印下边;
  • 从下到上 打印左边;

每打印完一层就缩小一圈范围,直到所有元素都被访问。

实现代码

cpp 复制代码
#include <vector>
using namespace std;

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

        int rows = matrix.size();
        int cols = matrix[ 0 ].size();

        // 定义当前圈的四个边界
        int top = 0, bottom = rows - 1;
        int left = 0, right = cols - 1;

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

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

            // 注意:可能只剩一行或一列的情况,需要判断是否还存在下边和左边
            if ( top <= bottom )
            {
                // 3. 从右到左
                for ( int i = right; i >= left; --i )
                {
                    result.push_back( matrix[ bottom ]`在这里插入代码片`[ i ] );
                }
                bottom--;  // 下边界上移
            }

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

        return result;
    }
};

#include <iostream>

int main()
{
    vector< vector< int > > matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

    Solution sol;
    vector< int > result = sol.spiralOrder( matrix );

    cout << "顺时针打印结果:" << endl;
    for ( int num : result )
    {
        cout << num << " ";
    }

    return 0;
}

运行结果

bash 复制代码
顺时针打印结果:
1 2 3 6 9 8 7 4 5 
相关推荐
jarreyer1 天前
python离线包安装方法总结
开发语言·python
李辰洋1 天前
go tools安装
开发语言·后端·golang
wanfeng_091 天前
go lang
开发语言·后端·golang
绛洞花主敏明1 天前
go build -tags的其他用法
开发语言·后端·golang
ByteCraze1 天前
秋招被问到的常见问题
开发语言·javascript·原型模式
码银1 天前
【python】基于 生活方式与健康数据预测数据集(Lifestyle and Health Risk Prediction)的可视化练习,附数据集源文件。
开发语言·python·生活
Pluchon1 天前
硅基计划5.0 MySQL 叁 E-R关系图&联合/多表查询&三大连接&子查询&合并查询
开发语言·数据库·学习·mysql
kyle~1 天前
C++---嵌套类型(Nested Types)封装与泛型的基石
开发语言·c++·算法
sali-tec1 天前
C# 基于halcon的视觉工作流-章48-短路断路
开发语言·图像处理·人工智能·算法·计算机视觉
无敌最俊朗@1 天前
解决 QML 中使用 Qt Charts 崩溃的三个关键步骤
开发语言·qt