【LeetCode】48. Rotate Image
来源:互联网 发布:故宫淘宝与故宫旗舰店 编辑:程序博客网 时间:2024/06/06 01:10
算法小白,最近刷LeetCode。希望能够结合自己的思考和别人优秀的代码,对题目和解法进行更加清晰详细的解释,供大家参考^_^
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?
将一个n×n的二维矩阵顺时针旋转90度,题目让输出旋转后的矩阵。这道题不难,关键是要搞清楚旋转之后的元素和旋转之前的元素的对应位置。
例如90度旋转之前,第i行第j列(
另一个要注意的是:90度旋转过程中其实只涉及四个位置的元素,如上面所说,d[i][j]这个元素旋转之后到了d[j][n+1-i]的位置,则原来在d[j][n+1-i]这个位置的元素旋转后到了d[n+1-i][n+1-j]的位置,依次类推,其实就是4个位置的元素,按照顺时针方向进行了交换。例如d[1][1]->d[1][n],d[1][n]->d[n][n],d[n][n]->d[n][1],d[n][1]->d[1][1]。
理解了上面这些,代码写起来就容易了:
class Solution {public: void rotate(vector<vector<int>>& matrix) { int len = matrix.size(); int x = len - 1; for (int i = 0; i < len / 2; ++i) { for (int j = i; j < len-1-i; ++j) { int tmp = matrix[i][j]; matrix[i][j] = matrix[x-j][i]; matrix[x-j][i] = matrix[x-i][x-j]; matrix[x-i][x-j] = matrix[j][x-i]; matrix[j][x-i] = tmp; } } }};
阅读全文
0 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
- 48. Rotate Image LeetCode
- [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
- ASP.NET页面输出XML(C#)
- .NET 在线生成XML文档,并提供下载
- 多进程爬虫
- 专注于windows系统安全 与 asp.net开发
- .Net读取xlsx文件Excel2007
- 【LeetCode】48. Rotate Image
- HBase1.2.0 windows单机版安装配置
- CodeForces
- 观察者模式--众多通知,一步到位(行为模式06)
- 纯CSS美化表格单元格背景效果,效果很帅
- UBUNTU系统镜像定制
- 二叉树的非递归遍历方法
- 调试svo 中遇到的问题
- Django 之 (6)模型(数据库)