矩阵相关算法

矩阵旋转90度

给定一个 n × n 的二维矩阵 matrix 表示一个图像,请你将图像顺时针旋转 90 度。

cpp 复制代码
#include <iostream>
#include <vector>

using namespace std;

void rotate(vector<vector<int>>& matrix) {
    int n = matrix.size();

    // 第一步:转置矩阵
    for (int i = 0; i < n; ++i) {
        for (int j = i + 1; j < n; ++j) {
            swap(matrix[i][j], matrix[j][i]);
        }
    }

    // 第二步:反转每一行
    for (int i = 0; i < n; ++i) {
        std::reverse(matrix[i].begin(), matrix[i].end());
    }
}

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

    rotate(matrix);

    // 输出结果
    for (const auto& row : matrix) {
        for (const auto& elem : row) {
            cout << elem << " ";
        }
        cout << endl;
    }

    return 0;
}

螺旋矩阵

将一个矩阵中的元素按照从右到左,从上到下,从右到左,从下到上依次输出

cpp 复制代码
#include <iostream>
#include <vector>

using namespace std;

vector<int> spiralOrder(const 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--;

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

		//防止上面right--越界
        if (left <= right) {
            // 从下到上遍历左边界
            for (int i = bottom; i >= top; i--) {
                result.push_back(matrix[i][left]);
            }
            left++;
        }
    }

    return result;
}

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

    vector<int> result = spiralOrder(matrix);
    
    // 输出结果
    for (int num : result) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}
相关推荐
森焱森21 分钟前
水下航行器外形分类详解
c语言·单片机·算法·架构·无人机
QuantumStack2 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
天若有情6732 小时前
01_软件卓越之道:功能性与需求满足
c++·软件工程·软件
whoarethenext3 小时前
使用 C++/OpenCV 和 MFCC 构建双重认证智能门禁系统
开发语言·c++·opencv·mfcc
写个博客3 小时前
暑假算法日记第一天
算法
绿皮的猪猪侠3 小时前
算法笔记上机训练实战指南刷题
笔记·算法·pta·上机·浙大
hie988944 小时前
MATLAB锂离子电池伪二维(P2D)模型实现
人工智能·算法·matlab
Jay_5154 小时前
C++多态与虚函数详解:从入门到精通
开发语言·c++
杰克尼4 小时前
BM5 合并k个已排序的链表
数据结构·算法·链表
.30-06Springfield5 小时前
决策树(Decision tree)算法详解(ID3、C4.5、CART)
人工智能·python·算法·决策树·机器学习