机器人的运动范围

这篇博客探讨了一种使用HashMap优化广度优先搜索(BFS)的空间效率的方法。作者通过创建一个以字符串键的HashMap来记录已访问的节点,避免了使用二维数组可能导致的空间浪费。文章详细介绍了实现过程,包括节点定义、移动方向数组、判断坐标合法性函数以及核心的BFS算法。这种方法在解决特定类型的网格问题时,可以有效减少内存消耗。
摘要由CSDN通过智能技术生成

简单的一道广搜题,我看大部分题解都是用二维数组来标记是否点被访问过,可能会造成空间浪费,用HashMap以String作为key的方法来解一下。



import java.util.*;
class Node{
    int x,y;
    Node(int x,int y){
        this.x=x;
        this.y=y;
    }
}
public class Solution {
    static HashMap<String,Boolean>map;
    static Queue<Node>queue=new LinkedList<>();
    static int xMove[]={1,0,-1,0};
    static int yMove[]={0,1,0,-1};
    static boolean isTrue(int x,int y,int threshold){//不能进入行坐标和列坐标的数位之和大于k的格子
        int sum=0;
        while (x>0){
            sum+=(x%10);
            x/=10;

       }
        while (y>0){
            sum+=(y%10);
            y/=10;
        }
        if(sum>threshold)
            return false;
        return true;
    }
   /* @Test
    public void test(){
        Scanner scanner=new Scanner(System.in);
        *//*int threshold=scanner.nextInt();
        int rows=scanner.nextInt();
        int cols=scanner.nextInt();*//*
        System.out.print(movingCount(10,30,30));
    }*/

    public static int movingCount(int threshold, int rows, int cols){
        int sum=0;
        StringBuilder stringBuilder=new StringBuilder();
        if(threshold<0)
            return 0;
        map=new HashMap<>();
        map.clear();
        stringBuilder.append(0);
        stringBuilder.append(',');
        stringBuilder.append(0);
        String s;
         s=stringBuilder.toString();
         sum++;
         map.put(s,true);
         Node node=new Node(0,0);
         queue.offer(node);
         while (queue.isEmpty()==false){
             Node nodePoll=queue.poll();
             for(int i=0;i<4;i++){
                 int x=nodePoll.x+xMove[i];
                 int y=nodePoll.y+yMove[i];
                 if(x>=0&&y>=0&&x<rows&&y<cols&&isTrue(x,y,threshold)){
                     stringBuilder.setLength(0);
                     stringBuilder.append(x);
                     stringBuilder.append(',');
                     stringBuilder.append(y);
                     s=stringBuilder.toString();
                     if(map.get(s)==null){
                         Node nodeNew=new Node(x,y);
                         queue.offer(nodeNew);
                         sum++;
                         map.put(s,true);
                     }

                 }
             }
         }
        // stringBuilder.setLength(0);
        return sum;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值