【java】【伪代码】广度优先搜索模板

【java】【伪代码】广度优先搜索模板

/**
*返回目标根节点与目标节点之间的最短距离
*/
int BFS(Node root, Node target){
    Queue<Node> queue;//用于储存待处理的节点
    int step = 0;//用于纪录根节点到目标节点的最短路径
    //初始化
    add root to queue;
    //BFS
    while(queue is not empty){
        step = step+1;
        //迭代队列中已经存在的节点
        int size = queue.size();
        for(int i = 0; i < size; i++){
            Node cur = the first node in queue;
            return step if cur is target;
            for(Node next : the neighbors of cur){
                add next to queue;
            }
            remove the first node from queue;
        }
    }
    return -1; //没有从根节点通向目标节点的路径
}

有哈希表的版本:

/**
*返回目标根节点与目标节点之间的最短距离
*/
int BFS(Node root, Node target){
    Queue<Node> queue;
    Set<Node> used;
    int step = 0;//用于纪录根节点到目标节点的最短路径
    //初始化
    add root to queue;//用于储存待处理的节点
    add root to used;//用于存放所有访问过的节点
    // BFS
    while(queue is not empty){
        step = step + 1;
        //迭代队列中已经存在的节点
        int size = queue.size();
        for(int i = 0; i < size; i++){
            Node cur = the first node in queue;
            return step if cur is target;
            for(Node next : the neighbors of cur){
                if(next is not in used){
                    add next to queue;
                    add next to used;
                }
            }
            remove the first node from queue;
        }
    }
    return -1;//没有从根节点通向目标节点的路径
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值