之前一直没怎么做广度优先的题目,目前想写个A*算法,所以先拿广度优先练练手。
poj链接:http://poj.org/problem?id=3278
首先建立一个队列open,这里保存所有的open表内的节点。初始化的时候把第一个节点farmer加入队列,然后针对open表内的第一个节点进行搜索,每个节点都有三个字节点:分别对应-1,+1,*2。如果其中有目标节点(cow),那么搜索成功结束,若没有则把搜索节点加入到open表中,置visit标记为true,防止重复搜索。
Java代码:
Memory:5960K
Time:1938MS
package com.xujin;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
/*
* Author Xu.Jin
* Date 2013/3/26
*
* 广度优先搜索poj3278
*
*/
public class NewTest{
public static void main(String...args){
while(cin.hasNext()){
farmer = cin.nextInt();
cow = cin.nextInt();
//如果farmer大于cow,那么farmer只能一步一步后退到cow
if(farmer >= cow){
System.out.println(farmer - cow);
return;
}
else{
System.out.println(BFS(farmer, cow));
}
}
}
private static int BFS(int farmer, int cow){
open = new LinkedList<Integer>();
open.add(farmer);
visit[farmer] = true;
int parentNode, nextOpen;
while(!open.isEmpty()){
parentNode = open.peek();
open.remove(); //准确的说是放到close表中
for(int i = 0; i < 3; i++){
if(i == 0) nextOpen = parentNode - 1;
else if(i == 1) nextOpen = parentNode + 1;
else nextOpen = parentNode * 2;
if(nextOpen > MAX_SIZE - 1 || nextOpen < 0)
continue;
//查找是否有目标
if(nextOpen == cow) return steps[parentNode] + 1;
if(!visit[nextOpen]){
open.add(nextOpen);
visit[nextOpen] = true;
steps[nextOpen] = steps[parentNode] + 1;
}
}
}
return -1;
}
private static int farmer;
private static int cow;
static Scanner cin = new Scanner(System.in);
private static Queue<Integer> open;
private static int MAX_SIZE = 100001;
private static boolean[] visit = new boolean[MAX_SIZE];
private static int[] steps = new int[MAX_SIZE];
}