剑指 Offer 13 机器人的运动范围 深度优先、广度优先算法题解

 题目主要考察深度优先和广度优先搜索算法,核心为根据一个二维数组来保存查找状态(是否已被遍历过),再根据x,y未超过m,n、没有被遍历过、各位数和不超过k来做边界条件,最后要注意加上自己(0,0)题目 力扣icon-default.png?t=M4ADhttps://leetcode.cn/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/

package leetcode.May;

import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @description:
 * @author: qiangyuecheng
 * @date: 2022/5/18 15:33
 */
public class Robots {
    public int get(int i, int j) {
        int res = 0;
        while (i + j > 0) {
            res += i % 10 + j % 10;
            i /= 10;
            j /= 10;
        }
        return res;
    }

    /**
     * 广度优先搜索 BFS
     */
    public int BFS(int m, int n, int k) {
        int res = 1;
        Queue<int[]> queue = new ArrayDeque();
        int[][] status = new int[m][n];
        queue.offer(new int[]{0, 0});
        //向右移动
        int[] tx = {1, 0};
        //想下移动
        int[] ty = {0, 1};
        while (!queue.isEmpty()) {
            int[] tmp = queue.poll();
            int x = tmp[0];
            int y = tmp[1];
            for (int i = 0; i <= 1; i++) {
                int tmpx = x + tx[i];
                int tmpy = y + ty[i];
                if (tmpx >= m || tmpy >= n || status[tmpx][tmpy] != 0 || get(tmpx, tmpy) > k) {
                    continue;
                } else {
                    status[tmpx][tmpy] = 1;
                    res += 1;
                    queue.offer(new int[]{tmpx, tmpy});
                }
            }
        }
        return res;
    }


    /**
     * 深度优先搜索 DFS
     */
    static int[] tx = new int[]{1, 0};
    static int[] ty = new int[]{0, 1};

    public int DFS(int m, int n, int k) {
        int[][] source = new int[m][n];
        return toDFS(source, 0, 0,m,n, k)+1;
    }

    public int toDFS(int[][] sou, int x, int y, int m, int n, int k) {
        if (x >= m || y >= n || get(x, y) > k||sou[x][y]==1) {
            return 0;
        }
        sou[x][y]=1;
        int res = 0;
        for (int i = 0; i < 2; i++) {
            res+=toDFS(sou,x+tx[i],y+ty[i],m,n,k);
        }
        return res+1;
    }

    public static void main(String[] args) {
        Robots robots = new Robots();

        System.out.println(robots.BFS(1, 2, 1));

        System.out.println(robots.DFS(1, 2, 1));
        
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值