mybloger

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

19、螺旋矩阵

image-20250610202945935

class Solution {
    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;
    }
}

20、旋转图像

image-20250610210559912

class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        for (int i = 0;i < n/2;i++) {
            for (int j = 0;j < (n + 1) / 2;j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[n - j - 1][i];
                matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1];
                matrix[n - i - 1][n - j -1] = matrix[j][n - i - 1];
                matrix[j][n - i - 1] = temp;
            }
        }
    }
}
posted on 2025-06-10 21:07  万能包哥  阅读(11)  评论(0)    收藏  举报