concept
Breadth-first and depth-first search
BFS uses FIFO and minimizes edge count; DFS uses LIFO and finds a reachable goal on a finite graph with cycle handling. Neighbor order can change ties. These are example functions, not Python built-ins.
Formal Syntax & Structure
artificial-intelligence syntaxartificial-intelligence
bfs(graph, start, goal) → path or None; dfs(graph, start, goal) → path or NoneWorking Example
Example Snippetartificial-intelligence
from collections import deque
def bfs(graph, start, goal): frontier = deque([[start]]) seen = {start} while frontier: path = frontier.popleft() state = path[-1] if state == goal: return path for neighbor in graph[state]: if neighbor not in seen: seen.add(neighbor) frontier.append(path + [neighbor]) return None
graph = {"A": {"B": 2, "C": 2, "G": 9}, "B": {"A": 2, "D": 1}, "C": {"G": 2}, "D": {"G": 2}, "G": {}, "X": {}}print(bfs(graph, "A", "G"))print(bfs(graph, "A", "X"))