给定一个 n × n 的二维矩阵表示一个图像。
将图像顺时针旋转 90 度。
说明:
你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。
示例 1:
给定 matrix = [
[1,2,3],
[4,5,6],
[7,8,9] ],
原地旋转输入矩阵,使其变为: [
[7,4,1],
[8,5,2],
[9,6,3] ]
示例 2:
给定 matrix = [
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16] ],
原地旋转输入矩阵,使其变为: [
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11] ]
这个题的意思是给你一个2D的图像(我们知道2D图像是由(x,y)像素点组成的),题目要求我们将这幅图形顺时针旋转90度,确实是一个比较有趣的题目。
如果你是第一次拿到这个题的话确实比较难动手,但是一旦你见过这类似的题目(比如:剑指offer上面的螺旋数组),那么你就瞬间有思路了。我先画个图解释一下这个题的思路:
主要思路也是由外向里,每次旋转掉一层,重复上面操作,知道循环到最里面,这时候就完成了整体的旋转。
源代码:GCC
1#include <stdio.h>
2#include <stdlib.h>
3
4static void rotate_one(int** matrix, int size, int circle)
5{
6 //如size=5,i=0,那么max = 4
7 //max是最大的下标
8 int max = size - 2 * circle - 1;
9 int tmp = 0;
10
11 //从第max个数开始旋转,不用旋转到[0]
12 for (int i = max; i >= 1; --i)
13 {
14 //[0,0]号位置
15 tmp = matrix[circle][circle + i];
16 //每次计算四个边的四个位置
17 matrix[circle][circle + i] = matrix[circle + max - i][circle];
18 matrix[circle + max - i][circle] = matrix[circle + max][circle + max - i];
19 matrix[circle + max][circle + max - i] = matrix[circle + i][circle + max];
20 matrix[circle + i][circle + max] = tmp;
21 }
22}
23
24void rotate(int** matrix, int matrixRowSize, int matrixColSizes) {
25 //如5,只需要2次旋转
26 for (int i = 0; i < matrixRowSize / 2; ++i) {
27 rotate_one(matrix, matrixRowSize, i);
28 }
29}
30
31
32int main(int argc, char **argv)
33{
34 if (argc != 3) {
35 printf("Usage: ./test 3 3\n");
36 }
37
38 int i, j, count = 0;
39 int row_size = atoi(argv[1]);
40 int col_size = atoi(argv[2]);
41 int **matrix = malloc(row_size * sizeof(int *));
42 for (i = 0; i < row_size; i++) {
43 matrix[i] = malloc(col_size * sizeof(int));
44 for (j = 0; j < col_size; j++) {
45 matrix[i][j] = ++count;
46 printf("%d ", matrix[i][j]);
47 }
48 printf("\n");
49 }
50
51 rotate(matrix, row_size, col_size);
52 for (i = 0; i < col_size; i++) {
53 for (j = 0; j < row_size; j++) {
54 printf("%02d ", matrix[i][j]);
55 }
56 putchar('\n');
57 }
58
59 return 0;
60}