螺旋矩阵 II (Spiral Matrix II)

 

思路:

// @Title: 螺旋矩阵 II (Spiral Matrix II)
// @Author: qisiii
// @Date: 2024-09-11 23:37:43
// @Runtime: 0 ms
// @Memory: 40.3 MB
// @comment: 
// @flag: 
class Solution {
    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        int count = 1, target = n * n;
        int left = 0, right = n - 1, top = 0, bottom = n - 1;
        int i , j ;
        while (count <= target) {
            for ( i = left; count <= target&&i <= right; i++) {
                result[top][i] = count++;
            }
            top++;
            for ( j = top; count <= target&&j <= bottom; j++) {
                result[j][right] = count++;
            }
            right--;
            for ( i = right;count <= target&& i >= left; i--) {
                result[bottom][i] = count++;
            }
            bottom--;
            for ( j = bottom; count <= target&&j >= top; j--) {
                result[j][left] = count++;
            }
            left++;
        }
        return result;
    }
}

+++ title = “螺旋矩阵 II (Spiral Matrix II)” draft = false +++

思路:

// @Title: 螺旋矩阵 II (Spiral Matrix II)
// @Author: qisiii
// @Date: 2024-05-17 10:39:50
// @Runtime: 0 ms
// @Memory: 40.5 MB
// @comment: 
// @flag: 
class Solution {
    public int[][] generateMatrix(int n) {
        int[][] matrix=new int[n][n];
        int top=0,left=0,right=matrix[0].length-1,bottom=matrix.length-1;
        int index=1;
        int total=matrix.length*matrix[0].length;
        while(index<=total){
            for(int i=left;i<=right&&index<=total;i++){
                matrix[top][i]=index++;
            }
            top++;
            for(int i=top;i<=bottom&&index<=total;i++){
                matrix[i][right]=index++;
            }
            right--;
            for(int i=right;i>=left&&index<=total;i--){
                matrix[bottom][i]=index++;
            }
            bottom--;
            for(int i=bottom;i>=top&&index<=total;i--){
                matrix[i][left]=index++;
            }
            left++;
        }
        return matrix;
    }

}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18