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

本站现有博文332篇,共被浏览886407

本站已经建立2590天!

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