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

本站现有博文311篇,共被浏览740101

本站已经建立2377天!

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