Implemented an animated demonstration of Breadth First Search (BFS) using the Pygame module. First, the structure of a graph is represented by an adjacency matrix, where each node represents a character and the neighbors of each character represent the nodes adjacent to it. Then, the nodes are accessed in hierarchical order through a breadth-first search algorithm, and the changes at each step are visualized through animation effects. Each time a node is visited, the node turns green and its adjacent edges turn black, forming an animation effect of breadth-first search. The algorithm uses queues to maintain nodes at the current level and gradually expands to the next level. This demonstration visually demonstrates the level traversal process of breadth-first search on the graph through moderate delay and color changes, helping to understand how the algorithm expands the search path layer by layer.
Complete implementation code:
import pygame
import sys
from collections import deque
# 初始化 Pygame
pygame.init()
# 定义颜色
WHITE =