0
点赞
收藏
分享

微信扫一扫

LeetCode-048-旋转图像

月白色的大狒 2021-09-28 阅读 57
LeetCode

旋转图像

解法一:数组遍历
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();
        }
    }
}
举报

相关推荐

0 条评论