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

本站现有博文328篇,共被浏览839584

本站已经建立2544天!

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