home *** CD-ROM | disk | FTP | other *** search
- #include <new.h>
- #include "search.h"
-
- /* SEARCH_
-
- The constructor puts the start node on open, saves the goal node
- and sets the number of operators to the specified value.
-
- */
-
- SEARCH_::SEARCH_(NODE_ *start, NODE_ *goal, int op)
- {
- open.addtohead(*start); // put the start node on open
- num_op = op;
- goalnode = goal;
- }
-
-
-
- /* ~SEARCH_
-
- The destructor only deallocates the memory occupied by the goalnode.
-
- */
-
- SEARCH_::~SEARCH_()
- {
- delete(goalnode);
- }
-
-
-
- /* PRINT_SOL
-
- Prints the solution by tracing back through the parent *'s. So, we
- recurse a little (well...)
-
- */
-
- void SEARCH_::print_sol(NODE_ *sol) const
- {
- if (!sol)
- return;
- print_sol(sol->getparent());
- sol->display();
- }
-
-
-
- /* GENERATE
-
- Starts the search process by calling solve() and prints the
- solution if found by calling print_sol().
-
- */
-
- #ifdef MSC
- extern int no_mem(size_t);
- #else
- extern void no_mem();
- #endif
-
- void SEARCH_::generate()
- {
- NODE_
- *sol;
-
- #ifdef MSC
- _set_new_handler(no_mem);
- #else
- set_new_handler(no_mem);
- #endif
-
- if (!(sol = solve()))
- {
- puts("No solution found");
- return;
- }
-
- print_sol(sol);
- }
-
-
-
- /* SOLVE
-
- This routines implements the actual search engine. It takes the first
- node from OPEN, if OPEN is empty the search process fails. If not, the
- node is moved to CLOSED. Next, the node's successors are generated by
- calling NODE_::expand(). Then, every successor is made to point
- back to its parent, so that the solution path may be traced back once
- the solution is found. Each successor is passed to add() for further
- processing, if add() returns 0 this means that the the successor
- already was on OPEN and consequently it can be thrown away, i.e. it gets
- deallocated.
-
- Solve() returns the goal node if found and NULL otherwise.
- */
-
- NODE_ *SEARCH_::solve()
- {
- NODE_
- *father,
- *child,
- *next;
-
- while((father = (NODE_ *) open.gethead()) != NULL)
- { // get first node from open
- open.remove_head();
- closed.addtohead(*father); // put it on closed
-
- if (goalnode->equal(*father)) // found a goal node
- return(father);
-
- child = father->expand(num_op); // expand the node
- while (child)
- {
- child->setparent(father); // so I can remember my daddie
- next = child->getnext();
- if (!add(child))
- delete(child); // child aready in graph: kill it!
- child = next;
- }
- }
- return(NULL);
- }
-
-