[剑指offer] 机器人的运动范围

北慕城南 提交于 2019-11-27 13:59:23

题目

https://www.acwing.com/problem/content/description/22/

思路

bfs。yxc大佬说如果数据大的时候c++写dfs可能会爆栈。

Java代码

import java.util.LinkedList;

class Solution {

    int[] dx = new int[]{-1, 0, 1, 0};
    int[] dy = new int[]{0, 1, 0, -1};

    public int movingCount(int threshold, int rows, int cols){
        if(rows == 0 || cols == 0) return 0;
        int res = 0;
        boolean[][] st = new boolean[rows][cols];
        LinkedList<int[]> q = new LinkedList<>();
        q.add(new int[]{0, 0});
        while(!q.isEmpty()){
            int[] t = q.pop();
            if(sum(t[0])+sum(t[1]) > threshold || st[t[0]][t[1]] == true)
                continue;
            
            res++;
            st[t[0]][t[1]] = true;
            for(int i=0; i<4; i++){
                int x = rows+dx[i], y = rows+dy[i];
                if(t[0] >= 0 && t[0] <rows && t[1] >=0 && t[1] < cols)
                    q.add(new int[]{t[0], t[1]});
            }
        }
        return res;
    }

    private static int sum(int x){
        int ret = 0;
        while(x !=0 ){
            ret += x%10;
            x /= 10;
        }
        return ret;
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!