home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Hacker Chronicles 2
/
HACKER2.BIN
/
635.BFS
< prev
next >
Wrap
Text File
|
1989-02-18
|
2KB
|
29 lines
BFS Algorithm (* breadth-first search *)
(* Search a graph or state space, depending on the problem definition. *)
(* S is the start node, T is the goal node. *)
(* Open is an ordered list of nodes (ordered by arrival time; nodes enter
at the tail and leave at the head), also called a queue. Closed is a set
of nodes (order doesn't matter). In general, nodes that need to be
searched are put on Open. As they are searched, they are removed from
Open and put in Closed. *)
(* Pred is defined for each node, and is a list of "came from" indications,
so when we finally reach T, we traverse Pred to construct a path to S. *)
1 Open <- {S} (* a list of one element *)
Closed <- {} (* the empty set *)
Pred[S] <- NULL, found <- FALSE
WHILE Open <> {} and not found DO
5 x <- the first node on Open
Open <- Open - {x} (* remove x from Open *)
Closed <- Closed + {x} (* put x in Closed *)
IF x = T THEN found <- TRUE (* we're done *)
ELSE (* continue search through node x *)
10 let R be the set of neighboring nodes of x
FOR each y in R DO
IF y is not on Open or in Closed THEN
Pred[y] <- x (* remember where we came from *)
Open <- Open + {y} (* put y on Open (at the tail) *)
15 IF found THEN
use Pred[T] to find Pred[Pred[T]] and so on until S is reached
(* this traces out the solution path in reverse *)
ELSE T cannot be reached from S