您的位置:首页 > 编程语言 > Java开发

Leet Code 48 Rotate Image - 旋转图片 - Java

2016-06-23 00:00 169 查看
摘要: Leet Code 48 Rotate Image - 旋转图片 - Java

问题原始链接 https://leetcode.com/problems/rotate-image

给定一个 n*n 的二维数组,表示一张图片,把该图片顺时针旋转90度。

public class Solution {
public static void rotate(int[][] matrix) {
if (matrix == null || matrix.length <= 1) {
return;
}

for (int i = 0; i < matrix.length / 2; i++) {
rotateCircle(matrix, i);
}
}

private static void rotateCircle(int[][] matrix, int i) {
int step = matrix.length - 1 - i * 2;
for (int j = i; j < matrix.length - 1 - i; j++) {
int nextRow = -1;
int nextCol = -1;
int curRow = i;
int curCol = j;
int temp = matrix[curRow][curCol];
do {
nextRow = getNextRow(matrix, i, step, curRow, curCol);
nextCol = getNextCol(matrix, i, step, curRow, curCol);
int t = matrix[nextRow][nextCol];
matrix[nextRow][nextCol] = temp;
temp = t;
curRow = nextRow;
curCol = nextCol;
} while (nextRow != i || nextCol != j);
}
}

private static int getNextRow(int[][] matrix, int n, int step, int i, int j) {
int max = matrix.length - 1 - n;
if (i == n && j >= n && j < max) {
return j + step <= max ? n : n + (j + step - max);
}
if (i >= n && i < max && j == max) {
return max;
}
if (i == max && j > n && j <= max) {
return j - step >= n ? max : max - (n - (j - step));
}
if (i > n && i <= max && j == n) {
return n;
}
return i;
}

private static int getNextCol(int[][] matrix, int n, int step, int i, int j) {
int max = matrix.length - 1 - n;
if (i == n && j >= n && j < max) {
return max;
}
if (i >= n && i < max && j == max) {
return i + step <= max ? max : max - (i + step - max);
}
if (i == max && j > n && j <= max) {
return n;
}
if (i > n && i <= max && j == n) {
return i - step >= n ? n : n + (n - (i - step));
}
return j;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息