博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode c语言-Rotate Image
阅读量:7051 次
发布时间:2019-06-28

本文共 1632 字,大约阅读时间需要 5 分钟。

Title:

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Note:

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:

Given input matrix = [  [1,2,3],  [4,5,6],  [7,8,9]],rotate the input matrix in-place such that it becomes:[  [7,4,1],  [8,5,2],  [9,6,3]]

Example 2:

Given input matrix =[  [ 5, 1, 9,11],  [ 2, 4, 8,10],  [13, 3, 6, 7],  [15,14,12,16]], rotate the input matrix in-place such that it becomes:[  [15,13, 2, 5],  [14, 3, 4, 1],  [12, 6, 8, 9],  [16, 7,10,11]]

 

这道题是将一个矩阵旋转90度,需要的是不用额外的数组空间来完成,因此要找规律,规律如下:

[  [1,2,3],  [4,5,6],  [7,8,9]],
变换为:

[  [7,4,1],  [8,5,2],  [9,6,3]]

转换成数组形式,也就是:

[0,0] [0,1] [0,2]

[1,0] [1,1] [1,2]

[2,0] [2,1] [2,2]

旋转90度如下:

[2,0] [1,0] [0,0]

[2,1] [1,1] [0,1]

[2,2] [1,2] [0,2]

因此规律很明显,对于每一行,顺序颠倒即可,比如第一行,[0,0]变换后为[2,0],也就是将第一行最后一个数字[0,2]的行与列调换,然后与第一个[0,0]调换即可。比如第二行[1,0]与第二行最后一个[1,2],[1,2]首先调换行与列[2,1],然后与第二行第一个[1,0]调换,当然[1,0]也要行列调换为[0,1]。

solution:

void rotate(int** matrix, int matrixRowSize, int matrixColSize) {    int i,j;    int tmp[matrixRowSize][matrixColSize];    int used[matrixRowSize][matrixColSize];        memset(tmp,0,sizeof(tmp));    memset(used,0,sizeof(used));    for (i=0;i

这个解法有一个缺陷,新建了两个二维数组。

那么如果不新建数组完成呢,要用到另一种思路:首先以从对角线为轴翻转,然后再以x轴中线上下翻转即可得到结果。

1  2  3       9  6  3       7  4  1

4  5  6  -->   8  5  2   -->     8  5  2  

7  8  9       7  4  1       9  6  3

solution:

void rotate(int** matrix, int matrixRowSize, int matrixColSize) {    int i,j;    int tmp;    for (i=0;i

转载于:https://www.cnblogs.com/sichenzhao/p/9320204.html

你可能感兴趣的文章
SQL Server中的锁
查看>>
ubuntu搭建nodejs生产环境——快速部署手册
查看>>
从零开始实现一个简易的Java MVC框架
查看>>
【java解惑】Unicode转义符的使用
查看>>
spring线程池ThreadPoolTaskExecutor与阻塞队列BlockingQueue
查看>>
visio图片导入word和PPT的最清晰的方式
查看>>
DataGuard 环境rman恢复主库坏块一例
查看>>
交换机真的只工作在第二层吗?
查看>>
15年编程生涯,资深架构师总结的7条经验
查看>>
echo命令
查看>>
图形语言 Kgo
查看>>
兄弟连第10节课
查看>>
调整Virtual Box硬盘大小
查看>>
Windows下Apache服务器中自动配置二级子域名
查看>>
Transform Map - Ignore Row if any fields are empty
查看>>
iEclipse-不只是Eclipse的开发者社区
查看>>
Oracle个人的一些记录
查看>>
20.分屏查看命令 less命令
查看>>
感谢付费客户不覺流年似水(271558528) 对C#ASP.NET通用权限管理组件的改进意见,已修正...
查看>>
android 让 TextView 自带滚动条
查看>>