题目描述:给定一个 n × n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。java
你必须在 原地 旋转图像,这意味着你须要直接修改输入的二维矩阵。请不要 使用另外一个矩阵来旋转图像。segmentfault
示例说明请见LeetCode官网。数组
来源:力扣(LeetCode)
连接:https://leetcode-cn.com/probl...
著做权归领扣网络全部。商业转载请联系官方受权,非商业转载请注明出处。网络
首先,寻找规律,找到当前节点要替换到哪一个位置,寻找到的规律是
(x, y)
位置的数字通过顺时针旋转90度以后要放在(y, matrix.length - 1 - x)
这个位置,而后还有一个规律是,顺时针旋转90度时,实际上是每4个节点旋转了一周,因此具体的处理过程以下:url
- 从数组的第一位开始遍历,x和y分别为坐标位,初始都为0,count为全部的节点总数,last为当前位置的值,用一个一样大小的数组flag记录每个位置是否已是被替换过的值;
根据规律获取应该被替换的节点
(nextX, nextY)
,判断这个节点是否已经被替换:code
- 若是已经被替换过,则遍历数组,寻找下一个未被替换的节点,而且初始化x和y为当前节点的坐标,temp为当前节点的值,而后进行下一次处理;
- 若是没有被替换过,则将当前节点的值替换为last,并用last记录替换以前的值,而后更新x和y为当前值的坐标,并更新当前位置为true即已替换,并将count减一。
- 循环中断的条件就是count为0,即已经将全部节点都处理完成。
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(); } } }
【每日寄语】 愿你昨晚的坏情绪,在今日掀开被子,拉开窗帘的那一刻,杳无踪迹。