Leetcode - Rotate Image

19 篇文章 0 订阅
[分析]
自己的思路:从外到内一圈圈顺时针旋转90度,坐标映射问题。
Leetcode讨论区有很多有趣巧妙的思路,列举两个点赞率较高思路:
1)上下颠倒,然后转置
/*
* clockwise rotate
* first reverse up to down, then swap the symmetry
* 1 2 3 7 8 9 7 4 1
* 4 5 6 => 4 5 6 => 8 5 2
* 7 8 9 1 2 3 9 6 3
*/
2)转置,然后左右颠倒
若需要逆时针,则分别是:
1)左右颠倒,然后转置
2)转置,然后上下颠倒
[ref]
[url]https://leetcode.com/discuss/20589/a-common-method-to-rotate-the-image[/url]


public class Solution {
public void rotate1(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return;
int rowBeg = 0, rowEnd = matrix.length - 1;
int colBeg = 0, colEnd = matrix[0].length - 1;
while (rowBeg <= rowEnd) {
int offset = colEnd - colBeg - 1;
for (int j = 0; j <= offset; j++) {
int save = matrix[rowBeg][colBeg + j];
matrix[rowBeg][colBeg + j] = matrix[rowEnd - j][colBeg];
matrix[rowEnd - j][colBeg] = matrix[rowEnd][colEnd - j];
matrix[rowEnd][colEnd - j] = matrix[rowBeg + j][colEnd];
matrix[rowBeg + j][colEnd] = save;
}
rowBeg++; rowEnd--;
colBeg++; colEnd--;
}
}
// first transpose, then flip the matrix horizontally
public void rotate(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return;
int rows = matrix.length, cols = matrix[0].length;
for (int i = 0; i < rows; i++) {
for (int j = i + 1; j < cols; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
int half = cols / 2;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < half; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[i][cols -1 - j];
matrix[i][cols -1 - j] = tmp;
}
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值