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

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

本站已经建立2629天!

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