求解迷宫问题
# 寻找迷宫路径
# DFS-深度优先搜索
from enum import Enum
from typing import TypeVar, Iterable, Sequence, Generic, List, Callable, Set, Deque, Dict, Any, Optional, NamedTuple
import random
from math import sqrt
# from .generic_search import dfs, bfs,node_to_path, astar, Node
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
self._container: List[T] = []
@property
def empty(self) -> bool:
return not self._container
def push(self, item: T) -> None:
self._container.append(item)
def pop(self) -> T:
return self._container.pop()
def __repr__(self):
return repr(self._container)
# 用于记录搜索时的状态
class Node(Generic[T]):
# Optional类型表示,参数化类型的值可以被变量引用,或变量可以引用None
# annotations允许Node在其方法的类型提示中引用自身
def __init__(self, state: T, parent: Optional['Node'], cost: float = 0.0, heuristic: float = 0.0) -> None:
self.state: T = state
self.parent: Optional[Node] = parent
self.cost: float = cost
self.heuristic: float = heuristic
def __lt__(self, other: 'Node') -> bool:
return (self.cost + self.heuristic) < (other.cost + other.heuristic)
def dfs(initial: T, goal_test: Callable[[T], bool], successors: Callable[[T], List[T]]) -> Optional[Node[T]]:
frontier: Stack[Node[T]] = Stack()
frontier.push(Node(initial, None))
explored: Set[T] = {initial}
while not frontier.empty:
current_node: Node[T] = frontier.pop()
current_state: T = current_node.state
if goal_test(current_state):
return current_node
for child in successors(current_state):
if child in explored:
continue
explored.add(child)
frontier.push(Node(child, current_node))
return None
def node_to_path(node: Node[T]) -> List[T]:
path: List[T] = [node.state]
while node.parent is not None:
node = node.parent
path.append(node.state)
path.reverse()
return path
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# BFS-广度优先搜索
# A*算法
编辑 (opens new window)
上次更新: 2022/05/25, 16:53:28