← Back

Program 2: Implement Depth-First Search (DFS) on a small graph.

Simple Python Code
def dfs_graph(graph, start, goal, visited=None, path=None):
    #DFS to find a path in a graph
    if visited is None:
        visited = set()
    if path is None:
        path = []
    
    visited.add(start)
    path = path + [start]
    
    if start == goal:
        return path
    
    for neighbor in graph.get(start, []):
        if neighbor not in visited:
            result = dfs_graph(graph, neighbor, goal, visited, path)
            if result:
                return result
    
    return None

print("DFS on Graph:")
graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': ['F'],
    'F': []
}
dfs_path = dfs_graph(graph, 'A', 'F')
print(f"DFS Path from A to F: {dfs_path}\n")
Advanced Python Code
def dfs_graph(graph, start, goal, visited=None, path=None):
    #DFS to find a path in a graph
    if visited is None:
        visited = set()
    if path is None:
        path = []
    
    visited.add(start)
    path = path + [start]
    
    if start == goal:
        return path
    
    for neighbor in graph.get(start, []):
        if neighbor not in visited:
            result = dfs_graph(graph, neighbor, goal, visited, path)
            if result:
                return result
    
    return None

print("DFS on Graph:")
graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': ['F'],
    'F': []
}
dfs_path = dfs_graph(graph, 'A', 'F')
print(f"DFS Path from A to F: {dfs_path}\n")
Infographics