EADST

C++矩阵旋转90度

题目:

请编写一个函数 rotateMatrix90,将一个 n x n 的二维矩阵顺时针旋转 90 度,并返回旋转后的矩阵。

要求: 1. 原矩阵可以在原地修改,不需要额外的矩阵。 2. 使用 O(1) 的额外空间。

输入示例:

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

输出示例:

{
    {7, 4, 1},
    {8, 5, 2},
    {9, 6, 3}
}

提示: 1. 可以先对矩阵进行转置(行列互换),然后翻转每一行来实现旋转。 2. 该方法适用于 n x n 的矩阵。


解答示例代码:

#include < vector>
#include < algorithm>
#include < iostream>

using namespace std;

void rotateMatrix90(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) {
        reverse(matrix[i].begin(), matrix[i].end());
    }
}

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

    rotateMatrix90(matrix);

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

    return 0;
}

代码解释:

  1. 转置矩阵:对矩阵进行转置操作,将行和列交换。
  2. 翻转每一行:使用 reverse 函数翻转每一行,从而实现 90 度旋转。
相关标签
About Me
XD
Goals determine what you are going to be.
Category
标签云
ModelScope Review 顶会 FP32 BF16 CV Plotly Base64 LLM CUDA Miniforge 净利润 Pytorch Password XML GoogLeNet Hungarian Google Python MD5 TSV PDF OpenAI 多线程 CSV Crawler Transformers SQLite WebCrawler 论文速读 Nginx Anaconda Algorithm DeepStream Llama DeepSeek Search Pillow 签证 Claude Distillation NLP 财报 FastAPI hf GIT Streamlit Proxy PIP 腾讯云 Heatmap Ubuntu Logo 报税 Math printf Cloudreve Mixtral Hilton 音频 ONNX PyCharm Template FlashAttention 算法题 Agent mmap v0.dev BTC Use transformers Jetson TensorFlow llama.cpp 图形思考法 Datetime BeautifulSoup HaggingFace Ptyhon Gemma Michelin Bipartite logger PyTorch SQL Vim SAM 阿里云 搞笑 Paddle 多进程 强化学习 IndexTTS2 Qwen Disk NLTK icon Paper CC LaTeX Knowledge Breakpoint VSCode Card NameSilo CLAP Docker ResNet-50 CAM Git 继承 CTC LeetCode Random COCO Interview 公式 Food v2ray XGBoost Shortcut Web Bitcoin WAN LLAMA Clash GPTQ tar Dataset FP64 scipy JSON HuggingFace Django torchinfo API GPT4 TTS EXCEL Domain Freesound FP8 YOLO Quantization Magnet Video Bin PDB Website Pickle Qwen2.5 QWEN OpenCV Data diffusers InvalidArgumentError Tracking Zip Image2Text Vmess RAR Input Conda SPIE ChatGPT 域名 Excel Firewall 证件照 Safetensors Github CEIR Sklearn 关于博主 Jupyter 飞书 LoRA git-lfs FP16 Land Baidu Rebuttal Bert 递归学习法 Animate Tiktoken SVR uwsgi TensorRT VPN tqdm Pandas Windows News Linux 版权 Tensor Diagram 论文 图标 RGB C++ Qwen2 AI UNIX Augmentation ms-swift uWSGI Quantize Attention Permission Plate Statistics Hotel 云服务器 Markdown VGG-16 第一性原理 UI git Color GGML OCR Numpy Translation
站点统计

本站现有博文330篇,共被浏览861506

本站已经建立2570天!

热门文章
文章归档
回到顶部