📜  dfs and bfs inn python (1)

📅  最后修改于: 2023-12-03 15:00:24.642000             🧑  作者: Mango

Introduction to DFS and BFS in Python

DFS (Depth First Search) and BFS (Breadth First Search) are two of the most common graph traversal algorithms. They are widely used in solving many problems related to graphs, such as finding the shortest path, detecting cycles, and so on.

DFS

DFS is a recursive algorithm that traverses the graph by exploring as far as possible along each branch before backtracking. This means that it goes as deep as possible before exploring the other branches.

Here's an example implementation of the DFS algorithm in Python:

# DFS function
def DFS(graph, start, visited=None):
    if visited is None:
        visited = set()
    visited.add(start)
    print(start)
    for next in graph[start] - visited:
        DFS(graph, next, visited)
    return visited

The DFS function takes three parameters: the graph, the starting node, and a set of visited nodes (which is optional). It first adds the starting node to the visited set, prints the value of the starting node and then recursively calls itself on all unvisited neighbors of the starting node.

BFS

BFS is another popular graph traversal algorithm that explores all the vertices at the same level before moving on to the next level. This means that it goes breadth-wise instead of depth-wise.

Here's an example implementation of the BFS algorithm in Python:

# BFS function
def BFS(graph, start):
    visited, queue = set(), [start]
    while queue:
        vertex = queue.pop(0)
        if vertex not in visited:
            visited.add(vertex)
            print(vertex)
            queue.extend(graph[vertex] - visited)
    return visited

The BFS function takes two parameters: the graph and the starting node. It initially adds the starting node to both the visited set and the queue. It then continues to remove nodes from the queue until it is empty, adding any unvisited neighbors to the queue.

Conclusion

DFS and BFS are powerful algorithms for traversing graphs in different ways. Depending on the problem you're trying to solve, one of these algorithms may be better suited than the other. With these examples, you should have a good starting point to implement DFS and BFS functions in your own Python code.