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

本站现有博文333篇,共被浏览909417

本站已经建立2612天!

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