LeetCode 之 Rotate Image — C/C++ 实现
2015-06-11 14:24
561 查看
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?
给定一个 n×n 的二维矩阵代表一幅图像。
将图像按顺时针旋转90度。
附加:
能否在原位置操作?
分析:
法1:先将图像按次对角线翻转,再将图像上下部分翻转。
void rotate(int** matrix, int matrixRowSize, int matrixColSize) { int row = 0, col = 0; int temp = 0; if(!matrix || (matrixRowSize == 0 && matrixColSize == 0))/*空指针或空矩阵*/ { return; } /*先沿右上和左下对角线翻转*/ for(row = 0; row < matrixRowSize - 1; ++row) /*对角线不变*/ { for(col = 0; col < (matrixColSize - row - 1); ++col) { temp = matrix[row][col]; matrix[row][col] = matrix[matrixColSize-col-1][matrixRowSize-row-1]; matrix[matrixColSize-col-1][matrixRowSize-row-1] = temp; } } /*再上下对翻*/ for(row = 0; row < (matrixRowSize >> 1); ++row)/*只翻上半部分*/ { for(col = 0; col < matrixColSize; ++col) { temp = matrix[row][col]; matrix[row][col] = matrix[matrixRowSize-row-1][col]; matrix[matrixRowSize-row-1][col] = temp; } } return; }
法2:找到每个点该翻转的位置直接翻转。
<pre name="code" class="html">class Solution { public: void rotate(vector<vector<int>>& matrix) { if(matrix.empty()) { return; } int rowSize = matrix.size(); int rotateTimes = 0; int temp = 0; for(int ncycle = 0; ncycle < rowSize/2; ++ncycle) //由外圈向内圈一圈一圈的旋转移动 { rotateTimes = (rowSize - 2*ncycle) - 1;//移动次数 for(int pos = 0; pos < rotateTimes; ++pos)//移动一圈数据 { temp = matrix[pos + ncycle][ncycle]; matrix[ncycle + pos][ncycle] = matrix[ncycle + rotateTimes][ncycle + pos]; matrix[ncycle + rotateTimes][ncycle + pos] = matrix[ncycle + rotateTimes - pos][ncycle + rotateTimes]; matrix[ncycle + rotateTimes - pos][ncycle + rotateTimes] = matrix[ncycle][ncycle + rotateTimes - pos ]; matrix[ncycle][ncycle + rotateTimes - pos] = temp; } } return; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解
- LeetCode 2: Add Two Numbers (JAVA)
- LeetCode 1: Two Sum (JAVA)