我已经坚持这个问题好几天了。显然我需要编写一个更好的算法来赢得下面的算法。以下代码是从着名的Aima文件实现的。这里有专家可以指导我如何赢得算法吗?
(defun find-closest (list)
(x (car (array-dimensions list)))
(y (cadr (array-dimensions list)))
(let ((elems (aref list x y)))
(dolist (e elems)
(when (eq (type-of e) type)
(return-from find-closest (list x y)))) nil))
我尝试实施DFS但失败了,我不知道为什么。以下是我的代码。
(defun find-closest (list)
(let ((open (list list))
(closed (list))
(steps 0)
(expanded 0)
(stored 0))
(loop while open do
(let ((x (pop open)))
(when (finished? x)
(return (format nil "Found ~a in ~a steps.
Expanded ~a nodes, stored a maximum of ~a nodes." x steps expanded stored)))
(incf steps)
(pushnew x closed :test #'equal)
(let ((successors (successors x)))
(incf expanded (length successors))
(setq successors
(delete-if (lambda (a)
(or (find a open :test #'equal)
(find a closed :test #'equal)))
successors))
(setq open (append open successors))
(setq stored (max stored (length open))))))))
答案 0 :(得分:4)
查看代码,函数find-some-in-grid
返回type
的第一个找到的内容。从本质上讲,这将给你一个n * m世界的O(n * m)时间(想象一个世界,你在每一行都有一个污垢,在“最左边”和“最右边”之间交替。
由于你可以提取所有污垢位置的列表,你可以建立一个最短的遍历,或者至少是一个短于转储的遍历,而不是挑选你发现的任何污垢,先找到你最接近的(一些距离度量,从代码看起来你有曼哈顿距离(也就是说,你只能沿X轴移动Y轴,而不能同时移动两个)。这应该给你一个至少同样好的机器人作为愚蠢的遍历机器人并且经常更好,即使它不是最佳的。
条款是我没有书和基础实现纯粹基于你的问题,这样的事情可能有用:
(defun find-closest-in-grid (radar type pos-x pos-y)
(labels ((distance (x y)
(+ (abs (- x pos-x))
(abs (- y pos-y)))))
(destructuring-bind (width height)
(array-dimensions radar)
(let ((best nil)
((best-distance (+ width height))))
(loop for x from 0 below width
do (loop for y from 0 below height
do (loop for element in (aref radar x y)
do (when (eql (type-of element) type)
(when (<= (distance x y) best-distance)
(setf best (list x y))
(setf best-distance (distance x y))))))))
best)))