旋转图像
解法一:数组遍历
public class LeetCode_048 {
public static void rotate(int[][] matrix) {
boolean[][] flag = new boolean[matrix.length][matrix.length];
int count = matrix.length * matrix.length;
int x = 0, y = 0, temp, last = matrix[0][0];
while (count > 0) {
int nextX = y, nextY = matrix.length - 1 - x;
if (flag[nextX][nextY]) {
// 下一个节点已替换,寻找下一个未替换的节点
for (int i = x; i < matrix.length; i++) {
boolean isFound = false;
for (int j = 0; j < matrix.length; j++) {
if (!flag[i][j]) {
x = i;
y = j;
last = matrix[x][y];
isFound = true;
break;
}
}
if (isFound) {
break;
}
}
} else {
// 下一个节点没有被替换,则替换之,并且将之标记为已替换
temp = matrix[nextX][nextY];
matrix[nextX][nextY] = last;
last = temp;
count--;
x = nextX;
y = nextY;
flag[nextX][nextY] = true;
}
}
}
public static void main(String[] args) {
int[][] matrix = new int[][]{{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}};
rotate(matrix);
for (int[] ints : matrix) {
for (int anInt : ints) {
System.out.print(anInt + " ");
}
System.out.println();
}
}
}