59. Spiral Matrix II

思路:找规律
第一次向右走n步,第二次向下走n-1, 第3次向左走n-1,第4次向上走n-2,第5次向右走n-2……
注意二维数据index i,j和坐标轴x,y不要弄混了

public class Solution {
    public int[][] generateMatrix(int n) {
        int num[][] = new int[n][n];
        if (n == 0)
            return num;

        int i = 0,j = -1;  //模拟当前spiral order指针所在的位置, 第一次向右走后变成[0,0]
        int number = 0;
        int direction_i[] = {0, 0, -1, 1};  //左右上下
        int direction_j[] = {-1, 1, 0, 0};
        int direc = -1, count = 0, step = n;
        boolean repeated = true; //后面每个step都要走两次, 第一次设为true是因为n步只要走1次
        while(step > 0){
            //先找方向
            if (repeated == false){
                if ( (n - step) % 2 == 1){
                    direc = 3;
                }else{
                    direc = 2;
                }
            }else{
                if ((n - step) % 2 == 1){
                    direc = 0;
                }else{
                    direc = 1;
                }
            }


            //走step步
            count = step;
            while(count > 0){
                i += direction_i[direc];
                j += direction_j[direc];
                num[i][j] = ++number;
                count --;
            }


            if (repeated == true){
                step --;
                repeated = false;
            }else{
                repeated = true;
            }
        }
        return num;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值