How to write a depth-first search algorithm in Python?
How to write a depth-first search algorithm in Python?
Depth-First Search (DFS) is a commonly used graph traversal algorithm. In depth-first search, starting from the starting node, adjacent nodes are continuously explored until no more exploration is possible, and then it falls back to the previous node and continues to traverse unexplored adjacent nodes until all nodes are visited.
The following is an example of a depth-first search algorithm written in Python:
# 定义图的类 class Graph: def __init__(self, vertices): self.V = vertices # 节点数量 self.adj = [[] for _ in range(self.V)] # 存储节点的邻接节点 # 添加边 def add_edge(self, u, v): self.adj[u].append(v) # DFS递归函数 def dfs_util(self, u, visited): visited[u] = True # 标记当前节点为已访问 print(u, end=' ') # 输出当前节点 # 遍历当前节点的所有邻接节点 for i in self.adj[u]: if not visited[i]: self.dfs_util(i, visited) # 对外接口,执行DFS def dfs(self, u): visited = [False] * self.V # 标记所有节点均未访问 self.dfs_util(u, visited) # 测试代码 if __name__ == '__main__': # 创建一个具有4个节点的图 g = Graph(4) # 添加图的边 g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) print("深度优先遍历结果:") g.dfs(2)
The above code implements a Graph class to represent the structure of the graph, which includes the initial number of nodes and the definition of adjacent nodes . Then the function to add edges add_edge
is defined.
DFS algorithm is performed with the assistance of dfs_util
recursive function. The function accepts two parameters: the current node u
and an array visited
, using To mark whether the node has been visited. The algorithm first marks the current node as visited and outputs the value of the node. Then traverse all adjacent nodes of the current node. If the adjacent nodes have not been visited, the dfs_util
function is called recursively.
Finally, the dfs
function serves as the external interface, accepts the starting node as a parameter, and creates a visited
array initialized to False. Call the dfs_util
function to start DFS traversal.
In the test code, we create a graph with 4 nodes and add some edges. Then use starting node 2 to perform DFS traversal and output the results.
Hope this code example helps you understand how to write a depth-first search algorithm in Python. You can also modify and optimize the code according to your own needs.
The above is the detailed content of How to write a depth-first search algorithm in Python?. For more information, please follow other related articles on the PHP Chinese website!

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

The impact of homogeneity of arrays on performance is dual: 1) Homogeneity allows the compiler to optimize memory access and improve performance; 2) but limits type diversity, which may lead to inefficiency. In short, choosing the right data structure is crucial.

TocraftexecutablePythonscripts,followthesebestpractices:1)Addashebangline(#!/usr/bin/envpython3)tomakethescriptexecutable.2)Setpermissionswithchmod xyour_script.py.3)Organizewithacleardocstringanduseifname=="__main__":formainfunctionality.4

NumPyarraysarebetterfornumericaloperationsandmulti-dimensionaldata,whilethearraymoduleissuitableforbasic,memory-efficientarrays.1)NumPyexcelsinperformanceandfunctionalityforlargedatasetsandcomplexoperations.2)Thearraymoduleismorememory-efficientandfa

NumPyarraysarebetterforheavynumericalcomputing,whilethearraymoduleismoresuitableformemory-constrainedprojectswithsimpledatatypes.1)NumPyarraysofferversatilityandperformanceforlargedatasetsandcomplexoperations.2)Thearraymoduleislightweightandmemory-ef

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)
