leetcode885.SpiralMatrixIII

题目:按照顺时针顺序,把一个矩阵的每个位置遍历一遍。遍历时,圈子越来越大,不能走已经走过了的节点。而且,如果走到了矩阵的外边,那么依然可以走。返回的结果是遍历矩阵节点时的顺序。
输入:一个整型数组 前两位代表矩阵的行列数目,后两位代表起点的坐标
输出:二维数组,记录了顺时针依次走过的矩阵的坐标
别人思路:
1.在走螺旋的时候,其实是找规律右1、下1、左2、上2、右3、下3……,然后对应一下坐标的变化就是 (0,1)(1,0)(0,-1)(-1,0)其实就是 temp=x, x=y,y=-x
2.然后用step来记录1,2,3,4这种步长,再用n来记录下 没转完两个方向就调整一下步长。其中在矩阵中走过的点的坐标记录下来就OK啦

class Solution {
    public int[][] spiralMatrixIII(int R, int C, int r0, int c0) {
        int result[][] = new int[R*C][2] ;
        int count = 1 ;
        result[0][0] = r0 ;
        result[0][1] = c0 ;
        int x = 0 ;
        int y = 1 ;
        int n = 0 ;
        int step = 1;
        int temp ;
        while(count<R*C){
            //往一个方向走step步
            for(int i=0;i<step;i++) {
                r0 += x;
                c0 += y;
                //满足条件的坐标记录下来
                if (r0 >= 0 && r0 < R && c0 < C && c0 >= 0) {
                    result[count] = new int[]{r0, c0};
                    count++;
                }
            }
            n++;
            //完成两个方向后,步长增一
            if (n % 2 == 0) {
                step++;
            }
            //每次往一个方向走完后,调整变化坐标
            temp = x ;
            x = y ;
            y = -temp ;
        }
        return result ;
    }
}
class Solution {
    public int[][] spiralMatrixIII(int R, int C, int r0, int c0) {
        int res[][] = new int[R*C][2];
        res[0] = new int[]{r0, c0};
        int count = 1;
        int walk[][] = new int[][]{{0,1}, {1,0}, {0,-1},{-1,0}};
        int step = 1;
        // 0右 1下 2左 3上
        int spiral = 0;
        while(count < R * C){
            for(int i = 0; i < step; i++){
                r0 += walk[spiral][0];
                c0 += walk[spiral][1];
                if(r0 >= 0 && r0 < R && c0 >=0 && c0 < C){
                    res[count++] = new int[]{r0, c0};
                }
            }
            spiral = (spiral + 1) % 4;
            //每次走完右下或者左上后,步长加一
            if(spiral == 2 || spiral == 0){
                step++;
            }
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值