I have never made any questions about breadth-first. I want to write an A * algorithm, so I want to give it a higher priority.
Poj link: http://poj.org/problem? Id = 3278
First, create a queue open, where all nodes in the Open table are saved. During initialization, the first node farmer is added to the queue and then searched for the first node in the Open table. Each node has three Bytes: corresponding to-1, + 1, * 2. If a target node (COW) exists, the search is completed successfully. If no, add the search node to the Open table and Mark visit as true to prevent repeated searches.
Java code:
Memory: 5960 K
Time: 1938 Ms
Package COM. xujin; import Java. util. using list; import Java. util. queue; import Java. util. vertex;/** author Xu. jin * Date 2013/3/26 ** breadth-first search poj3278 **/public class newtest {public static void main (string... ARGs) {While (CIN. hasnext () {farmer = cin. nextint (); cow = cin. nextint (); // If farmer is greater than cow, farmer can only step back to cowif (farmer> = cow) {system. out. println (farmer-cow); return;} else {system. out. println (BFS (Fa Rmer, cow) ;}} Private Static int BFS (INT farmer, int cow) {open = new sort list <integer> (); open. add (farmer); visit [Farmer] = true; int parentnode, nextopen; while (! Open. isempty () {parentnode = open. peek (); open. remove (); // put it in the close table 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; // find whether the target 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 partition CIN = new partition (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];}