LeetCode: Rotate Image [047]
来源:互联网 发布:程序员考试通过条件 编辑:程序博客网 时间:2024/06/07 01:51
【题目】
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?
【题意】
给定一个nXn的二维矩阵,按时钟方向旋转90度,不能使用额外的数据结构
【思路】
从外向内逐层旋转
【代码】
class Solution {public: void rotateMatrix(vector<vector<int> >&matrix, int i, int j, int len){ //逐层旋转 //i,j 为当前层的左上角坐标 //len 为当前层的边长if(len<=1)return;//上边界第一个位置的坐标, 上边通过y_top递增1来访问后续位置int x_top=i, y_top=j;//右边界第一个位置的坐标,右边界通过x_right递增1来访问后续位置int x_right=i, y_right=j+len-1;//下边界第一个位置的坐标,下边界通过y_bottom递减1来访问后续位置int x_bottom=i+len-1, y_bottom=j+len-1;//左边界第一个位置的坐标,左边界通过x_left递减1来访问后续位置int x_left=i+len-1, y_left=j;while(y_top<j+len-1){//四个边界上对应位置顺时针轮换int temp=matrix[x_top][y_top];matrix[x_top][y_top]=matrix[x_left][y_left];matrix[x_left][y_left]=matrix[x_bottom][y_bottom];matrix[x_bottom][y_bottom]=matrix[x_right][y_right];matrix[x_right][y_right]=temp;//指向各边的下一个位置y_top++;x_right++;y_bottom--;x_left--;} } void rotate(vector<vector<int> > &matrix) { int len=matrix.size();int i=0, j=0;while(len>1){rotateMatrix(matrix, i, j, len);i++; j++;len-=2;} }};
0 0
- LeetCode: Rotate Image [047]
- LeetCode: Rotate Image
- [Leetcode] Rotate Image
- LeetCode : Rotate Image
- [LeetCode] Rotate Image
- leetcode 67: Rotate Image
- [leetcode] Rotate Image
- [Leetcode] Rotate Image
- [LeetCode]Rotate Image
- LeetCode-Rotate Image
- [leetcode] Rotate Image
- LeetCode - Rotate Image
- leetcode之Rotate Image
- LeetCode - Rotate Image
- Leetcode: Rotate Image
- LeetCode:Rotate Image
- Leetcode: Rotate Image
- Leetcode Rotate Image
- 单向链表是否成环
- 命令行下编译Cocos2d-x-3.0新建的项目以及在多平台上运行
- 关于前++和后++的区别
- 黑马程序员--IO流02--字节流
- PHP学习之Session和Cookies
- LeetCode: Rotate Image [047]
- 最大连续子序列
- 大话闽南话
- java自学之路-----File 和 Properties
- C++ fill() 、 fill_n & memset函数
- C++编写nodejs扩展实战
- 服务器端口大全
- Unity3D——添加剑痕效果(PocketRPG Trail插件)
- 从程序员飞升到CTO必须具备的六大能力