Algorithms
算法对于程序猿呢,就像习武之人的内功;有空闲时间就练一练,总是有好处的
topic
Given an n*n two-dimensional matrix matrix to represent an image. Please rotate the image 90 degrees clockwise.
Example:
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]]
problem solving ideas
Look carefully at the changes between the two-dimensional matrix before rotation and the two-dimensional matrix after rotation, you can get:
- The two-dimensional matrix is first exchanged up and down
- Re-diagonal replacement
Algorithm implementation code
void rotate(int matrix[][4], int matrixSize) {
int temp;
//上下交换
//得到
// 15 14 12 16
// 13 3 6 7
// 2 4 8 10
// 5 1 9 11
for (int i = 0; i < matrixSize/2; i++)
for (int j = 0; j < matrixSize; j++) {
temp = matrix[i][j];
matrix[i][j] = matrix[matrixSize - i - 1][j];
matrix[matrixSize - i - 1][j] = temp;
}
// 对角线交换 即可得到旋转二维矩阵
for (int i = 0; i < matrixSize - 1; i++) {
for (int j = i + 1; j < matrixSize; j++) {
temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
full code
#include <stdio.h>
void rotate(int matrix[][4], int matrixSize) {
int temp;
for (int i = 0; i < matrixSize/2; i++)
for (int j = 0; j < matrixSize; j++) {
temp = matrix[i][j];
matrix[i][j] = matrix[matrixSize - i - 1][j];
matrix[matrixSize - i - 1][j] = temp;
}
for (int i = 0; i < matrixSize - 1; i++) {
for (int j = i + 1; j < matrixSize; j++) {
temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
int main()
{
int matrix[4][4] = {
{
5,1,9,11},{
2,4,8,10},{
13,3,6,7},{
15,14,12,16} };
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
printf("\n\n\n");
rotate(matrix,4);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
printf("\n\n\n");
return 0;
}
written in the last words
不要认为算法在工作中用不到哦,都是可以用到的。
1. 比如这次顺时针旋转图片90度,在一些项目工作中就可以用到。Android Camera回到得到的图像数据就是需要顺时针旋转90度才可以竖着显示。
After rotating 90 degrees, the vertical image is obtained:
- For example, the picture obtained by obtaining screen information through MediaProjection is vertical. If this picture is input to the encoder or processed at the bottom layer, then it needs to be rotated 90 degrees counterclockwise before subsequent processing.