Figure 5: Partial implementation of depth-first algorithm for blocks problem

#define COUNT      2
#define TABLE     -1
#define MAX_DEPTH 99


struct node {
   int    number;
   int    blocks[COUNT+1];
   int    depth;
   struct node *parent;
   struct node *next;
};

struct node *CLOSED, *n, *newnode, *OPEN;

// Initialize this problem.
//          0
//          1 2   

OPEN   = NULL;
CLOSED = NULL;

b[0] = 1;
b[1] = TABLE;
b[2] = TABLE;
n    = create_new_node(node_number, b, 0);
node_number++;
add_to_list(&OPEN, &n);

// Make up a goal
//          0
//          1 
//          2  

goal[0] = 1;
goal[1] = 2;
goal[2] = TABLE;


while(searching){

   if(is_empty(OPEN))
      no_solution_exists(&searching);

   else{  /* OPEN list is not empty */

      n = remove_from_list(&OPEN);
      add_to_list(&CLOSED, &n);

      if(n->depth < MAX_DEPTH){

         for(i=0; i<=COUNT; i++){

/* RULE 1 */ if(is_uncovered(n, i)){

// Special case Try to move block i to the TABLE

               if(n->blocks[i] != TABLE){
/* RULE 3 */      if(state_doesnt_exist(OPEN, CLOSED, n, i, 
                        TABLE)){
                     newnode = 
                        move_block(n, node_number, i, TABLE);
                     if(is_a_goal_node(newnode, goal)){
                        solution_found(newnode, &searching);
                     }
                     node_number++;
                     add_to_list(&OPEN, &newnode);
                  }  /* ends state_doesnt_exist */
               }  /* ends if TABLE */

// Try to move block i onto block j 

               for(j=0; j<=COUNT; j++){
                  if(i != j){
/* RULE 2 */         if(is_uncovered(n, j)){
/* RULE 3 */            if(state_doesnt_exist(OPEN, CLOSED, n, 
                              i, j)){
                           newnode = move_block(n, node_number,
                                    i, j);
                           if(is_a_goal_node(newnode, goal)){
                              solution_found(newnode, &searching);
                           }
                           node_number++;
                           add_to_list(&OPEN, &newnode);
                        }  /* statedoesntexist */
                     }  /* ends if j is uncovered */
                  }  /* ends if i != j */
               }  /* ends loop over j */


            }  /* ends if is_uncovered */
         }  /* ends loop over i */
      }  /* ends if depth < MAX_DEPTH */
   }  /* ends else OPEN is not empty */
}  /* ends while searching */