Rotate image (C++ solution)

topic

Given an  ×  n  two-dimensional matrix  matrix representing an image. Please rotate the image 90 degrees clockwise.

You have to rotate the image in place, which means you need to modify the input 2D matrix directly. Please do not  use another matrix to rotate the image.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
 Output: [[7,4,1],[8,5,2],[9 ,6,3]]

Example 2:

Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
 Output: [[15 ,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

C++ solution

#include <iostream>
#include <vector>
using namespace std;

/*
* 定义旋转图像函数
* 复制一个同样数值的数组,从样例可以看出规律:
* 对于矩阵中第 i 行的第 j 个元素,在旋转后,它出现在第 j 列的第 n-i-1 个位置
*/
void rotate(vector<vector<int>>& matrix) {
	int n = matrix.size();
	auto matrix_new = matrix;
	for (int i = 0; i < n; ++i) {
		for (int j = 0; j < n; ++j) {
			matrix_new[j][n - i - 1] = matrix[i][j];
		}
	}
	matrix = matrix_new;
}
int main() {
	vector<vector<int>> matrix = { {1,2,3},{4,5,6},{7,8,9} };
	rotate(matrix);
	for (int i = 0; i < matrix.size(); ++i) {
		for (int j = 0; j < matrix.size(); ++j) {
			cout << matrix[i][j] << " ";
		}
		cout << endl;
	}
	cout << endl;
	return 0;
}

analyze

Define the rotate image function and copy an array with the same value. The pattern can be seen from the example: for the j-th element in the i-th row of the matrix, after rotation, it appears at the ni-1th position in the j-th column.

Guess you like

Origin blog.csdn.net/m0_62275194/article/details/133861211