【Leecode】Leecode刷题之路第54天之旋转矩阵

Scroll Down

题目出处

54-螺旋矩阵-题目出处

题目描述

54-螺旋矩阵-题目描述1
54-螺旋矩阵-题目描述2

个人解法

思路:

todo

代码示例:(Java)

todo

复杂度分析

todo

官方解法

54-旋转矩阵-官方解法

方法1:模拟

思路:

54-螺旋矩阵-模拟-思路

代码示例:(Java)

public class Solution1 {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> order = new ArrayList<Integer>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return order;
        }
        int rows = matrix.length, columns = matrix[0].length;
        boolean[][] visited = new boolean[rows][columns];
        int total = rows * columns;
        int row = 0, column = 0;
        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int directionIndex = 0;
        for (int i = 0; i < total; i++) {
            order.add(matrix[row][column]);
            visited[row][column] = true;
            int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
            if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]) {
                directionIndex = (directionIndex + 1) % 4;
            }
            row += directions[directionIndex][0];
            column += directions[directionIndex][1];
        }
        return order;
    }


}

复杂度分析

54-螺旋矩阵-模拟-复杂度分析

方法2:按层模拟

思路:

54-螺旋矩阵-按层模拟-思路1
54-螺旋矩阵-按层模拟-思路2

代码示例:(Java)

public class Solution2 {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> order = new ArrayList<Integer>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return order;
        }
        int rows = matrix.length, columns = matrix[0].length;
        int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
        while (left <= right && top <= bottom) {
            for (int column = left; column <= right; column++) {
                order.add(matrix[top][column]);
            }
            for (int row = top + 1; row <= bottom; row++) {
                order.add(matrix[row][right]);
            }
            if (left < right && top < bottom) {
                for (int column = right - 1; column > left; column--) {
                    order.add(matrix[bottom][column]);
                }
                for (int row = bottom; row > top; row--) {
                    order.add(matrix[row][left]);
                }
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return order;
    }


}

复杂度分析

54-螺旋矩阵-按层模拟-复杂度分析

考察知识点

收获

Gitee源码位置

54-旋转矩阵-源码

同名文章,已同步发表于CSDN,个人网站,公众号