当前位置: 首页 > news >正文

矩阵相关算法

矩阵旋转90度

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

#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;
}

螺旋矩阵

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

#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;
}

http://www.mrgr.cn/news/50496.html

相关文章:

  • 抖音电商推出运费险优惠 预计为商家一年降本超40亿元
  • ARM64使能kdump
  • 012集——CAD图中线段坐标导出到txt(CAD—C#二次开发入门)
  • 浅谈Java之接口
  • 【C】分支与循环1----if与switch
  • rust中编译宏控
  • AFSim仿真系统 --- 系统简解_11 行为与行为树
  • 苹果研究员质疑大模型!我们测试了6款,发现了4大真相
  • 病毒感染时间 题解 MarsCode
  • CST软件超表面--- 偏振片- 线圆极化转换,Floquet端口,S参数算轴比AR
  • GestaltMML——用于诊断罕见遗传疾病的多模态模型
  • 网站服务器监控:Lighttpd指标解读
  • numactl 设置 numa 内存分配规则
  • VUE项目基于源码实现可视化编程技术的探索
  • 【C语言教程】【常用类库】(十二)信号处理库 - <signal.h>
  • 【论文速读】字节跳动音乐生成模型 Seed-Music
  • keepalived实现高可用
  • Spark内置函数:字符串、日期和时间函数、聚合函数、数值函数、条件判断函数、窗口函数
  • YOLOv11改进策略【卷积层】| ECCV-2024 Histogram Transformer Block 适用于噪声大,图像质量低的检测任务
  • 学会分享是一种快乐的事情