力扣labuladong——一刷day21

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、力扣48. 旋转图像
  • 二、力扣54. 螺旋矩阵
  • 三、力扣59. 螺旋矩阵 II

通过图形变换处理旋转图像

前言

一、力扣48. 旋转图像

class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length-1;
        for(int i = 0; i < matrix.length; i ++){
            for(int j = i; j < matrix.length; j ++){
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp; 
            }
        }
        for(int i = 0; i <= n; i ++){
            for(int j = 0, k = n; j < k; j ++,k--){
                int temp = matrix[i][j];
                matrix[i][j] = matrix[i][k];
                matrix[i][k] = temp;
            }
        }
    }
}

二、力扣54. 螺旋矩阵

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        int row = matrix.length, col = matrix[0].length;
        int upRow = 0, downRow = row-1, leftCol = 0, rightCol = col-1;
        for(int a = 1; a <= row*col; ){
            for(int i = leftCol; i <= rightCol && a <= row*col; i ++){
                list.add(matrix[upRow][i]);
                a ++;
            }
            
            upRow ++;
            for(int i = upRow; i <= downRow && a <= row*col; i ++){
                list.add(matrix[i][rightCol]);
                a ++;
            }
            rightCol --;
            for(int i = rightCol; i >= leftCol && a <= row*col; i --){
                list.add(matrix[downRow][i]);
                a ++;
            }
            downRow --;
            for(int i = downRow; i >= upRow && a <= row*col; i --){
                list.add(matrix[i][leftCol]);
                a ++;
            }
            leftCol ++;
        }
        return list;
    }
}

三、力扣59. 螺旋矩阵 II

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int upRow = 0, downRow = n-1, leftCol = 0, rightCol = n-1;
        for(int a = 1; a <= n * n;){
            for(int i = leftCol; i <= rightCol && a <= n*n; i ++){
                matrix[upRow][i] = a++;
            }
            upRow ++;
            for(int i = upRow; i <= downRow && a <= n *n; i ++){
                matrix[i][rightCol] = a++;
            }
            rightCol --;
            for(int i = rightCol; i >= leftCol && a <= n * n; i --){
                matrix[downRow][i] = a++;
            }
            downRow --;
            for(int i = downRow; i >= upRow && a <= n*n; i --){
                matrix[i][leftCol] = a ++;
            }
            leftCol ++;
        } 
        return matrix;
    }
}

你可能感兴趣的:(力扣题解,leetcode,算法,职场和发展,数据结构,java)