;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: search/domains/grid-problem.lisp

;;;; Shortest Paths on a Grid

;;; A state is a cell (x y) of a WIDTH x HEIGHT grid.  The actions are the
;;; names of the DIRECTIONS, an alist from a name to the (dx dy) step; by
;;; default the four compass directions, and *DIRECTIONS8* adds the
;;; diagonals.  Each step costs 1.

(defparameter *directions4* '((W -1 0) (N 0 1) (E 1 0) (S 0 -1))
  "The four compass directions, as (name dx dy).")

(defparameter *directions8*
  (append *directions4* '((NW -1 1) (NE 1 1) (SE 1 -1) (SW -1 -1)))
  "The four compass directions and the four diagonals.")

(defstructure (grid-problem (:include problem))
  "Find a shortest path between two cells of a grid with obstacles."
  (width 10)
  (height 10)
  (obstacles nil)                       ; list of blocked cells (x y)
  (directions *directions4*))

(defun grid-passable? (problem cell)
  "Is CELL on the grid and free of obstacles?"
  (and (< -1 (first cell) (grid-problem-width problem))
       (< -1 (second cell) (grid-problem-height problem))
       (not (member cell (grid-problem-obstacles problem) :test #'equal))))

(defmethod successors ((problem grid-problem) state)
  "Step to each passable neighboring cell."
  (let ((result nil))
    (dolist (d (grid-problem-directions problem) (nreverse result))
      (let ((cell (list (+ (first state) (second d))
			(+ (second state) (third d)))))
	(when (grid-passable? problem cell)
	  (push (cons (first d) cell) result))))))

(defmethod h-cost ((problem grid-problem) state)
  "The Manhattan distance to the goal, or with diagonal moves the Chebyshev
  distance, so that h never overestimates."
  (let ((dx (abs (- (first state) (first (problem-goal problem)))))
	(dy (abs (- (second state) (second (problem-goal problem))))))
    (if (some #'(lambda (d) (and (/= (second d) 0) (/= (third d) 0)))
	      (grid-problem-directions problem))
	(max dx dy)
      (+ dx dy))))
