0
点赞
收藏
分享

微信扫一扫

59. 螺旋矩阵 II

小云晓云 2022-03-16 阅读 68

力扣icon-default.png?t=M276https://leetcode-cn.com/problems/spiral-matrix-ii/


//模拟
public class Solution {
    public int[][] GenerateMatrix(int n) {
        //C#二维数组初始化!!!
        var mat=new int[n][];
        for(int i=0;i<n;i++){
            mat[i]=new int[n];
        }
        int left=0;
        int right=n-1;
        int top=0;
        int bottom=n-1;
        int count=1;
        int tar=n*n;
        while(count<=tar){
            //从左到右
            //行不变列变
            for(int i=left;i<=right;i++){
                mat[top][i]=count++;
            }
            top++;
            //从上到下
            //行变列不变
            for(int i=top;i<=bottom;i++){
                mat[i][right]=count++;
            }
            right--;
            //从右到左
            //行不变列变
            for(int i=right;i>=left;i--){
                mat[bottom][i]=count++;
            }
            bottom--;
            //从下到上
            //行变列不变
            for(int i=bottom;i>=top;i--){
                mat[i][left]=count++;
            }
            left++;
        }
        return mat;
    }
}
举报

相关推荐

0 条评论