From f642cf8b20b18872f9564cb81c89006d1d99f4ff Mon Sep 17 00:00:00 2001 From: Haco Date: Sat, 29 May 2021 23:08:38 +0530 Subject: [PATCH] DepthFirstSearch(Iterative) It is dfs iterative version using array as stack --- .../DepthFirstSearchIterative.swift | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Depth-First Search/DepthFirstSearchIterative.swift diff --git a/Depth-First Search/DepthFirstSearchIterative.swift b/Depth-First Search/DepthFirstSearchIterative.swift new file mode 100644 index 000000000..805425066 --- /dev/null +++ b/Depth-First Search/DepthFirstSearchIterative.swift @@ -0,0 +1,35 @@ +// +// DepthFirstIterative.swift +// DFS +// +// Created by Yash Jivani on 29/05/21. +// + +import Foundation + +func depthFirstSearchIterative(_ graph: Graph, source: Node) -> [String]{ + var nodesExplored = [source.label] + + source.visited = true + + var stack : [Node] = [] + + stack.append(source) + while(!stack.isEmpty){ + + let top = stack.removeFirst() + + if(!top.visited){ + nodesExplored.append(top.label) + top.visited = true + } + + for edge in top.neighbors{ + if(!edge.neighbor.visited){ + stack.insert(edge.neighbor, at: 0) + } + } + + } + return nodesExplored +}