广度优先搜索

广度优先算法(BFS)(一般用队列来辅助,一般没有递归,用个走到的条件跳出while循环):是先把自己周围能到达的点先做完,然后再进行下一步,最先到达终点,那肯定是最佳路径。一般解决最短路径问题(SummerII  K,L题)

这里附上一题:

Gdufe_2018_Summer II

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

* Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

Input

Line 1: Two space-separated integers: N and K

Output

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

Sample Input

5 17

Sample Output

4

Hint

The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.

题解:输入两个点(起点和终点),对于一个点x,它有三种走法,第1种,x-1。第二种,x+2。第三种,x*2。问起点到达终点,用最少的步数是多少。很明显是一道广度优先搜索的裸题。

import java.util.LinkedList;
import java.util.Scanner;
class Node{
	int x=0,dept = 0;       //x用来记录当前的位置,dept记录当 前的步数
}
public class Main {
	static LinkedList<Node> q = new LinkedList<Node>();
	static Scanner scan = new Scanner(System.in);
	static int[] vis = new int[200000];      //记录点是否走过
	static int n,m;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		while(scan.hasNext()){
			n = scan.nextInt();
			m = scan.nextInt();
			int ans = bsf();
			System.out.println(ans);
		}
	}
	private static int bsf() {
		// TODO Auto-generated method stub
		for(int i=0;i<vis.length;i++){      //每次调用都必需初始化
			vis[i] = 0;
		}
		q.clear();
		Node node = new Node();
		node.x = n;
		vis[n] = 1;
		node.dept = 0;
		q.add(node);
		
		while(!q.isEmpty()){              //用队列帮助能达到广度优先的并列搜索
			Node node1 = new Node();
			node1 = q.poll();
			if(node1.x==m){
				return node.dept;
			}
			
			for(int i=1;i<=3;i++){
				Node node11 = new Node();
		//		System.out.println(node1.dept);
				
				if(i==1){				//i-1
					node11.x = node1.x-1;
				}
				if(i==2){
					node11.x = node1.x+1;
				}
				if(i==3){
					node11.x = node1.x*2;
				}
				node11.dept = node1.dept+1;
				if (node11.x == m)
				{
					return node11.dept;
				}
				if(node11.x>=0&&node11.x<200000&&vis[node11.x]==0){
					vis[node11.x] = 1;
					q.add(node11);
				}
			 }
		}	
		return 0;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值