剑指Offer打卡day8—— AcWing 24. 机器人的运动范围

【题目描述】
在这里插入图片描述

AcWing 24. 机器人的运动范围

DFS

【思路】
遍历每一个合法位置

class Solution {
    int ans = 0;
    int [][] dir = new int[][]{{-1, 0}, {0, 1}, {1, 0}, {0, - 1}};
    
    public int get_single_sum(int x){
        int res = 0;
        while(x > 0){
            res = res  + x % 10;
            x /= 10;
        }
        return res;
    }
    public int get_sum(int x, int y){
        return get_single_sum(x) + get_single_sum(y);
    }
    public void dfs(int k, int x, int y, boolean st[][]){
        if( get_sum(x, y) > k ) return;
        int m = st.length, n = st[0].length;
        st[x][y] = true;
        ans ++;
        
        for(int i = 0; i < 4; i ++){
            int nx = x +dir[i][0], ny = y + dir[i][1];
            if(nx >= 0 && nx < m && ny >=0 && ny < n && !st[nx][ny])
                dfs(k, nx, ny, st);
        }
    }
    
    public int movingCount(int threshold, int rows, int cols)
    {
        if(rows == 0 || cols == 0) return 0;
        boolean st[][] = new boolean[rows][cols];
        dfs(threshold, 0, 0, st);
        return ans;
    }
}

BFS

【思路】
BFS 统计队列中合法的且没有被访问过的点的且符合题意的个数

class node{
    int x, y;
    public node(int xx, int yy){
        x = xx;
        y = yy;
    }
}
class Solution {
    public int get_single_sum(int t){// 123
        int res = 0;
        while(t > 0){
            res = res + t % 10;
            t /= 10;
        }
        return res;
    }
    public int get_sum(int x, int y){
        return get_single_sum(x) + get_single_sum(y);
    }
    public int movingCount(int threshold, int rows, int cols)
    {
        //特判边界
        if( rows == 0 || cols == 0) return 0;
        int ans = 0;
        
        LinkedList<node> q = new LinkedList<node>();
        boolean st[][] = new boolean[rows][cols];
        int dir[][] = {{-1, 0}, {0, 1}, {1, 0}, {0,-1}};
        

        q.push(new node(0, 0));
        st[0][0] = true;
        ans ++;
       
        while(! q.isEmpty()){
            node head = q.peek();
            q.pop();

            for(int i = 0; i < 4; i ++){
                int nx = head.x +dir[i][0], ny = head.y +dir[i][1];
                 //每次扩展合法、没有遍历过的且符合题意
                 //(即该格子行坐标和列坐标的数位之和不大于 k)点到队列中 
                if( nx >= 0 && nx < rows && ny >= 0 && ny < cols && !st[nx][ny]
                    && get_sum(nx,ny) <= threshold ){
                    st[nx][ny] = true;
                    q.push(new node(nx, ny));
                    ans ++;
                }
                    
            }
        }
        return ans;
        
        
        
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值