矩阵相关算法

矩阵旋转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;
}
相关推荐
m0_626535202 分钟前
力扣题目练习 换水问题
python·算法·leetcode
第六五5 分钟前
DPC和DPC-KNN算法
人工智能·算法·机器学习
一匹电信狗5 分钟前
【LeetCode_160】相交链表
c语言·开发语言·数据结构·c++·算法·leetcode·stl
AA陈超34 分钟前
虚幻引擎5 GAS开发俯视角RPG游戏 P05-11 消息小部件
c++·游戏·ue5·游戏引擎·虚幻
再卷也是菜1 小时前
C++篇(14)二叉树进阶算法题
c++·算法
小邓儿◑.◑1 小时前
贪心算法 | 每周8题(三)
算法·贪心算法
十五年专注C++开发1 小时前
QDarkStyleSheet: 一个Qt应用的暗色主题解决方案
开发语言·c++·qt·qss
2401_841495641 小时前
【数据结构】最长的最短路径的求解
java·数据结构·c++·python·算法·最短路径·图搜索
小龙报1 小时前
《算法每日一题(1)--- 连续因子》
c语言·开发语言·c++·windows·git·算法·visual studio
祁同伟.1 小时前
【C++】异常
开发语言·c++