Skip to content

Commit f642cf8

Browse files
committed
DepthFirstSearch(Iterative)
It is dfs iterative version using array as stack
1 parent 5d55104 commit f642cf8

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
//
2+
// DepthFirstIterative.swift
3+
// DFS
4+
//
5+
// Created by Yash Jivani on 29/05/21.
6+
//
7+
8+
import Foundation
9+
10+
func depthFirstSearchIterative(_ graph: Graph, source: Node) -> [String]{
11+
var nodesExplored = [source.label]
12+
13+
source.visited = true
14+
15+
var stack : [Node] = []
16+
17+
stack.append(source)
18+
while(!stack.isEmpty){
19+
20+
let top = stack.removeFirst()
21+
22+
if(!top.visited){
23+
nodesExplored.append(top.label)
24+
top.visited = true
25+
}
26+
27+
for edge in top.neighbors{
28+
if(!edge.neighbor.visited){
29+
stack.insert(edge.neighbor, at: 0)
30+
}
31+
}
32+
33+
}
34+
return nodesExplored
35+
}

0 commit comments

Comments
 (0)