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

本站现有博文321篇,共被浏览763905

本站已经建立2439天!

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