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

本站现有博文330篇,共被浏览861463

本站已经建立2570天!

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