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
延伸文章資訊
- 1Depth First Search (DFS) C++ Program To Traverse A Graph ...
BFS vs DFS ; Stands for “Breadth-first search”, Stands for “Depth-first search” ; The nodes are e...
- 2Graph - 演算法筆記
DFS 的程式碼也可以寫成遞迴形式。程式語言中的遞迴,其實就是利用stack 來實作的。 bool adj[ ...
- 3Depth First Search (DFS) Algorithm - Programiz
Python, Java and C/C++ Examples
- 4[演算法] [C++ / Python] 深度優先搜尋Depth-First-Search - Part I
[演算法] [C++ / Python] 深度優先搜尋Depth-First-Search - Part I ... 更新:熱騰騰的Part II 出爐囉! 深度優先搜尋,Depth-First...
- 5BFS DFS(C++ ) - IT閱讀
BFS DFS(C++ ). /* A / \ B C / \ / \ D E F G 深度優先遍歷(DFS) : A B D E C F G 廣度優先遍歷(BFS) ...