Depth First Search (DFS) Algorithm - Programiz
文章推薦指數: 80 %
Python, Java and C/C++ Examples
CourseIndex
ExploreProgramiz
Python
JavaScript
C
C++
Java
Kotlin
Swift
C#
DSA
StartLearningDSA
PopularTutorials
QuicksortAlgorithm
MergeSortAlgorithm
LinkedListDataStructure
HashTableDataStructure
DynamicProgramming
Python
JavaScript
C
C++
Java
Kotlin
Swift
C#
DSA
StartLearningDSA
PopularTutorials
QuicksortAlgorithm
MergeSortAlgorithm
LinkedListDataStructure
HashTableDataStructure
DynamicProgramming
Viewalltutorials
Python
JavaScript
C
C++
Java
Kotlin
ExplorePythonExamples
PopularExamples
Addtwonumbers
Checkprimenumber
Findthefactorialofanumber
PrinttheFibonaccisequence
Checkleapyear
Viewallexamples
DSAIntroduction
Whatisanalgorithm?
DataStructureandTypes
WhylearnDSA?
AsymptoticNotations
MasterTheorem
DivideandConquerAlgorithm
DataStructures(I)
Stack
Queue
TypesofQueue
CircularQueue
PriorityQueue
Deque
DataStructures(II)
LinkedList
LinkedListOperations
TypesofLinkedList
HashTable
HeapDataStructure
FibonacciHeap
DecreaseKeyandDeleteNodeOperationsonaFibonacciHeap
TreebasedDSA(I)
TreeDataStructure
TreeTraversal
BinaryTree
FullBinaryTree
PerfectBinaryTree
CompleteBinaryTree
BalancedBinaryTree
BinarySearchTree
AVLTree
TreebasedDSA(II)
BTree
InsertioninaB-tree
DeletionfromaB-tree
B+Tree
InsertiononaB+Tree
DeletionfromaB+Tree
Red-BlackTree
Red-BlackTreeInsertion
Red-BlackTreeDeletion
GraphbasedDSA
GraphDataStructure
SpanningTree
StronglyConnectedComponents
AdjacencyMatrix
AdjacencyList
DFSAlgorithm
Breadth-firstSearch
BellmanFord'sAlgorithm
SortingandSearchingAlgorithms
BubbleSort
SelectionSort
InsertionSort
MergeSort
Quicksort
CountingSort
RadixSort
BucketSort
HeapSort
ShellSort
LinearSearch
BinarySearch
GreedyAlgorithms
GreedyAlgorithm
Ford-FulkersonAlgorithm
Dijkstra'sAlgorithm
Kruskal'sAlgorithm
Prim'sAlgorithm
HuffmanCoding
DynamicProgramming
DynamicProgramming
Floyd-WarshallAlgorithm
LongestCommonSequence
OtherAlgorithms
BacktrackingAlgorithm
Rabin-KarpAlgorithm
RelatedTopics
Breadthfirstsearch
AdjacencyList
GraphDataStucture
StronglyConnectedComponents
Dijkstra'sAlgorithm
AdjacencyMatrix
DepthFirstSearch(DFS)
Inthistutorial,youwilllearnaboutdepthfirstsearchalgorithmwithexamplesandpseudocode.Also,youwilllearntoimplementDFSinC,Java,Python,andC++.
DepthfirstSearchorDepthfirsttraversalisarecursivealgorithmforsearchingalltheverticesofagraphortreedatastructure.Traversalmeansvisitingallthenodesofagraph.
DepthFirstSearchAlgorithm
AstandardDFSimplementationputseachvertexofthegraphintooneoftwocategories:
Visited
NotVisited
Thepurposeofthealgorithmistomarkeachvertexasvisitedwhileavoidingcycles.
TheDFSalgorithmworksasfollows:
Startbyputtinganyoneofthegraph'sverticesontopofastack.
Takethetopitemofthestackandaddittothevisitedlist.
Createalistofthatvertex'sadjacentnodes.Addtheoneswhicharen'tinthevisitedlisttothetopofthestack.
Keeprepeatingsteps2and3untilthestackisempty.
DepthFirstSearchExample
Let'sseehowtheDepthFirstSearchalgorithmworkswithanexample.Weuseanundirectedgraphwith5vertices.
Undirectedgraphwith5verticesWestartfromvertex0,theDFSalgorithmstartsbyputtingitintheVisitedlistandputtingallitsadjacentverticesinthestack.
VisittheelementandputitinthevisitedlistNext,wevisittheelementatthetopofstacki.e.1andgotoitsadjacentnodes.Since0hasalreadybeenvisited,wevisit2instead.
Visittheelementatthetopofstack
Vertex2hasanunvisitedadjacentvertexin4,soweaddthattothetopofthestackandvisitit.
Vertex2hasanunvisitedadjacentvertexin4,soweaddthattothetopofthestackandvisitit.Vertex2hasanunvisitedadjacentvertexin4,soweaddthattothetopofthestackandvisitit.Afterwevisitthelastelement3,itdoesn'thaveanyunvisitedadjacentnodes,sowehavecompletedtheDepthFirstTraversalofthegraph.
Afterwevisitthelastelement3,itdoesn'thaveanyunvisitedadjacentnodes,sowehavecompletedtheDepthFirstTraversalofthegraph.DFSPseudocode(recursiveimplementation)
ThepseudocodeforDFSisshownbelow.Intheinit()function,noticethatweruntheDFSfunctiononeverynode.Thisisbecausethegraphmighthavetwodifferentdisconnectedpartssotomakesurethatwecovereveryvertex,wecanalsoruntheDFSalgorithmoneverynode.
DFS(G,u)
u.visited=true
foreachv∈G.Adj[u]
ifv.visited==false
DFS(G,v)
init(){
Foreachu∈G
u.visited=false
Foreachu∈G
DFS(G,u)
}
DFSImplementationinPython,JavaandC/C++
ThecodefortheDepthFirstSearchAlgorithmwithanexampleisshownbelow.Thecodehasbeensimplifiedsothatwecanfocusonthealgorithmratherthanotherdetails.
Python
Java
C
C++
#DFSalgorithminPython
#DFSalgorithm
defdfs(graph,start,visited=None):
ifvisitedisNone:
visited=set()
visited.add(start)
print(start)
fornextingraph[start]-visited:
dfs(graph,next,visited)
returnvisited
graph={'0':set(['1','2']),
'1':set(['0','3','4']),
'2':set(['0']),
'3':set(['1']),
'4':set(['2','3'])}
dfs(graph,'0')
//DFSalgorithminJava
importjava.util.*;
classGraph{
privateLinkedList
usingnamespacestd;
classGraph{
intnumVertices;
list
延伸文章資訊
- 1BFS DFS(C++ ) - IT閱讀
BFS DFS(C++ ). /* A / \ B C / \ / \ D E F G 深度優先遍歷(DFS) : A B D E C F G 廣度優先遍歷(BFS) ...
- 2[演算法] [C++ / Python] 深度優先搜尋Depth-First-Search - Part I
[演算法] [C++ / Python] 深度優先搜尋Depth-First-Search - Part I ... 更新:熱騰騰的Part II 出爐囉! 深度優先搜尋,Depth-First...
- 3C++中的遞迴深度優先搜尋(DFS)演算法 - 程式人生
【C++】C++中的遞迴深度優先搜尋(DFS)演算法. 2020-12-21 C++. 我已經將 Graph 類中的圖實現為具有所有訪問和修改它所需功能的鄰接矩陣,這是我在DFS演算法中所需的 ...
- 4Depth First Search (DFS) Algorithm - Programiz
Python, Java and C/C++ Examples
- 5Graph: Depth-First Search(DFS,深度優先搜尋)
DFSVisit(int vertex, int &time) :利用遞迴函式呼叫,進行 color 、 discover 、 finish 與 predecessor 等資料更新的主要函式。 ...