;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: search/algorithms/rbfs.lisp

;;;; Recursive Best-First Search (RBFS)

;;; RBFS mimics A* in linear space: it keeps only the current path and, for
;;; each node on it, the f-cost of the best alternative.  When it unwinds
;;; past a node it replaces the node's f-cost with the best f-cost of its
;;; children, so that it knows whether to come back to that subtree.

(defun recursive-best-first-search (problem)
  "Search with RBFS and return a solution node, or nil. [Fig. 3.22]"
  ;; Nodes are re-expanded when the search comes back to them.
  (setf (problem-iterative? problem) t)
  (values (rbfs problem (create-start-node problem) infinity)))

(defun rbfs (problem node f-limit)
  "Return a solution node (or nil) and a new f-cost limit."
  (if (goal-test problem (node-state node))
      (values node (node-f-cost node))
    ;; EXPAND already sets f = max(g + h, f of the parent).
    (let ((successors (expand node problem)))
      (if (null successors)
	  (values nil infinity)
	(loop
	 (setf successors (sort successors #'< :key #'node-f-cost))
	 (let ((best (first successors)))
	   (when (or (> (node-f-cost best) f-limit)
		     (>= (node-f-cost best) infinity))
	     (return (values nil (node-f-cost best))))
	   (let ((alternative (if (rest successors)
				  (node-f-cost (second successors))
				infinity)))
	     (multiple-value-bind (result new-f)
		 (rbfs problem best (min f-limit alternative))
	       (setf (node-f-cost best) new-f)
	       (when result
		 (return (values result new-f)))))))))))
