LeetCode 第 48 题(Rotate Image)
来源:互联网 发布:图画软件下载 编辑:程序博客网 时间:2024/05/18 07:28
LeetCode 第 48 题(Rotate Image)
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).Follow up:
Could you do this in-place?
将一个矩阵顺时针旋转 90 度。有两种常规做法,一种是下面这样,先对矩阵进行转置操作,然后再做个左右对称。每一个操作又可以分解为两两元素的位置交换。下面是代码:
void rotate(vector<vector<int>>& matrix) { int N = matrix.size(); // 先对矩阵转置 for(int y = 0; y < N; y ++) { for(int x = y; x < N; x++) { int t = matrix[y][x]; matrix[y][x] = matrix[x][y]; matrix[x][y] = t; } } // 然后做一次左右对称 for(int y = 0; y < N; y ++) { for(int x = 0; x < N/2; x++) { int t = matrix[y][x]; matrix[y][x] = matrix[y][N-1-x]; matrix[y][N-1-x] = t; } } }
还有一种做法,直接做旋转操作。旋转操作可以分解为一系列的四个像素点间的轮换操作。这样的操作可以一圈一圈的进行,先将矩阵最外围一圈算完,再向里面深入一层。直到最后进行到矩阵的中心位置。比如下面的矩阵,我们先来调换黄色的一圈元素。之后是绿色的一圈,最后是蓝色的。
按照这个思路,下面是代码:
void rotate(vector<vector<int>>& matrix) { int N = matrix.size(); for(int y = 0; y < (N + 1) / 2; y ++) { for(int x = y; x < N - 1 - y; x++) { int t = matrix[y][x]; matrix[y][x] = matrix[N-1-x][y]; matrix[N-1-x][y] = matrix[N-1-y][N-1-x]; matrix[N-1-y][N-1-x] = matrix[x][N-1-y]; matrix[x][N-1-y] = t; } }}
1 0
- LeetCode 第 48 题(Rotate Image)
- 【leetcode】第48题 Rotate Image 题目+解析+代码
- LeetCode(48)Rotate Image
- [leetcode 48] Rotate Image
- [LeetCode 48]Rotate Image
- leetcode || 48、Rotate Image
- leetcode-48 Rotate Image
- Rotate Image - LeetCode 48
- Leetcode 48: Rotate Image
- Leetcode #48 Rotate Image
- LeetCode(48) Rotate Image
- leetcode 48: Rotate Image
- Leetcode#48||Rotate Image
- leetcode 48:Rotate Image
- 【leetcode】【48】Rotate Image
- Leetcode 48 - Rotate Image
- LeetCode 48 - Rotate Image
- 【LeetCode-48】Rotate Image
- 【Codeforces696B】【寻找】
- (OK) [android-x86-6.0-rc1] grub - set timeout=5
- 比较常用的jQuery
- 欢迎使用CSDN-markdown编辑器
- C++ PP Chapter XI 使用类
- LeetCode 第 48 题(Rotate Image)
- CAP理论
- Spring IOC 创建bean实例的方式
- 文件的读写
- 韩信点兵算法
- Android启动模式与onNewIntent
- 二分图匹配(基础)——过山车 ( HDU 2063 )
- Git使用入门
- 机顶盒EPG菜单自动处理程序20131118