当前位置: 首页 > 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.lryc.cn/news/460196.html

相关文章:

  • 微信小程序-封装通用模块
  • Modnet 人像抠图(论文复现)
  • 利用session机制造测试账号,无需前端也可以测试后端接口
  • JAVA_18
  • Linux升级openssl版本
  • 多态对象的存储方案小结
  • Linux 之 nano 编辑器
  • zipkin启动脚本并指定mysql数据存储
  • 超越GPT-4的视觉与文本理解能力,开源多模态模型领跑者 - Molmo
  • 输入输出--I/O流【C++提升】()
  • Maven 中央仓库地址推荐
  • Fastgpt本地化部署 - 以MAC为例
  • SpringBoot框架下购物推荐网站的设计模式与实现
  • Apache Flink 和 Apache Kafka
  • Excel中Ctrl+e的用法
  • 07-Cesium动态处理线条闪烁材质的属性
  • postgresql16分区表解析
  • 文字识别解决方案-OCR识别应用场景解析
  • Qt 每日面试题 -9
  • K8s环境下使用sidecar模式对EMQX的exhook.proto 进行流量代理
  • Dirble:一款高性能目录扫描与爬取工具
  • C#语言基础
  • 网络分析仪——提升网络性能的关键工具
  • 简单认识Maven 1
  • 鼠标右键删除使用Visual Studio 打开(v)以及恢复【超详细】
  • 如何缩短微商城系统推广周期
  • 电脑如何清理重复文件?方法很简单!
  • 【Linux】ioctl分析
  • 物联网通信会给人们的生活带来什么样的变化
  • Android 中获取当前 CPU 频率和占用率