This commit is contained in:
onyx-and-iris 2024-01-11 18:28:03 +00:00
parent cc680c1807
commit ecf623c2c4
4 changed files with 90 additions and 0 deletions

BIN
chapter6/bfs1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

BIN
chapter6/bfs2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

42
chapter6/ex6.1.py Normal file
View File

@ -0,0 +1,42 @@
import logging
from collections import deque
from dataclasses import dataclass
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
@dataclass
class Node:
name: str
distance: int
graph = {
"s": [Node("a", 1), Node("b", 1)],
"a": [Node("c", 0), Node("f", 0)],
"b": [Node("c", 0), Node("d", 0)],
"c": [],
"d": [Node("f", 0)],
"f": [],
}
def bfs():
queue = deque()
queue += graph["s"]
while queue:
logger.debug(queue)
current_node = queue.popleft()
if current_node.name == "f":
return current_node.distance
next_nodes = graph[current_node.name]
for node in next_nodes:
node.distance = current_node.distance + 1
queue += next_nodes
distance = bfs()
print(f"shortest distance from s to f: {distance}")

48
chapter6/ex6.2.py Normal file
View File

@ -0,0 +1,48 @@
import logging
from collections import deque
from dataclasses import dataclass
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
@dataclass
class Node:
name: str
distance: int
graph = {
"cab": [Node("cat", 1), Node("car", 1)],
"cat": [Node("mat", 0), Node("bat", 0)],
"car": [Node("cat", 0), Node("bar", 0)],
"mat": [Node("bat", 0)],
"bar": [Node("bat", 0)],
"bat": [],
}
visited = []
def bfs():
queue = deque()
queue += graph["cab"]
while queue:
logger.debug(queue)
current_node = queue.popleft()
if current_node.name == "bat":
return current_node.distance
if current_node.name in visited:
continue
visited.append(current_node.name)
next_nodes = graph[current_node.name]
for node in next_nodes:
node.distance = current_node.distance + 1
queue += next_nodes
distance = bfs()
print(f"shortest distance from cab to bat: {distance}")