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 
相关推荐
肆忆_10 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星14 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛2 天前
delete又未完全delete
c++
端平入洛3 天前
auto有时不auto
c++
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20214 天前
信号量和信号
linux·c++
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc