力扣59 螺旋矩阵

class Solution {
    public int[][] generateMatrix(int n) {
        int [][] nums = new int[n][n];
        int start = 0 , offset = 1 ,count = 1;
        int i=0, j=0;
        int times = 0 ;
        while(times ++ < n/2 ){
            for( j =start; j< n-offset ; j++){
                nums[start][j] = count++ ;}
            for( i=start; i < n-offset ; i++){
                nums[i][j] = count++ ;}
            for( ; j>start ; j--){
                 nums[i][j] = count++ ;}
            for( ; i > start ; i--){
                nums[i][j] = count++ ;}
            start ++ ;
            offset ++ ;
        }if( n%2 == 1){
            int q = (1+n) / 2 -1 ;
            nums[q][q] = count ;
        }
        return nums ;
    }
}

总结:

1.利用while进行固定次数的循环,用的是定义times的方式。数学知识,转n/2圈。

2.第一次循环后 到第二次循环开始,从左至右的数组横坐标要用start,不能用i,上一次循环后的i是0,所以i必须更新到新的start。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值