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

本站现有博文322篇,共被浏览788983

本站已经建立2484天!

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