Posted on by Kalkicode
Code Graph

DFS traversal of directed graph in swift

Swift program for DFS traversal of directed graph. Here problem description and explanation.

import Foundation
/*
    Swift 4 program for 
    DFS traversal of directed graph using recursion
*/
class AjlistNode
{
	// Vertices node key
	var id: Int;
	var next: AjlistNode? ;
	init(_ id: Int)
	{
		// Set value of node key
		self.id = id;
		self.next = nil;
	}
}
class Vertices
{
	var data: Int;
	var next: AjlistNode? ;
	var last: AjlistNode? ;
	init(_ data: Int)
	{
		self.data = data;
		self.next = nil;
		self.last = nil;
	}
}
class Graph
{
	// Number of Vertices
	var size: Int;
	var node: [Vertices? ];
	init(_ size: Int)
	{
		// Set value
		self.size = size;
		self.node = Array(repeating: nil, count: size);
		self.setData();
	}
	// Set initial node value
	func setData()
	{
		if (self.size <= 0)
		{
			print("\nEmpty Graph");
		}
		else
		{
			var index: Int = 0;
			while (index < self.size)
			{
				// Set initial node value
				self.node[index] = Vertices(index);
				index += 1;
			}
		}
	}
	// Connect two nodes
	func connect(_ start: Int, _ last: Int)
	{
		let edge: AjlistNode? = AjlistNode(last);
		if (self.node[start]!.next == nil)
		{
			self.node[start]!.next = edge;
		}
		else
		{
			// Add edge at the end
			self.node[start]!.last!.next = edge;
		}
		// Get last edge 
		self.node[start]!.last = edge;
	}
	//  Handling the request of adding new edge
	func addEdge(_ start: Int, _ last: Int)
	{
		if (start >= 0 && start < self.size && last >= 0 && last < self.size)
		{
			// Safe connection
			self.connect(start, last);
		}
		else
		{
			// When invalid nodes
			print("\nHere Something Wrong");
		}
	}
	func printGraph()
	{
		if (self.size > 0)
		{
			var index: Int = 0;
			// Print graph ajlist Node value
			while (index < self.size)
			{
				print("\nAdjacency list of vertex " + String(index), 
                      terminator: " : ");
				var temp: AjlistNode? = self.node[index]!.next;
				while (temp  != nil)
				{
					// Display graph node 
					print(self.node[temp!.id]!.data, 
                          terminator: "  ");
					// visit to next edge
					temp = temp!.next;
				}
				index += 1;
			}
		}
	}
	// Dfs traversal of given node point
	func dfs(_ visit: inout[Bool], _ point: Int)
	{
		if (visit[point])
		{
			// We already visited this node
			return;
		}
		// Set active node visit
		visit[point] = true;
		// Display visiting node point
		print("  " + String(point), terminator: "");
		// Get node edge  
		var temp: AjlistNode? = self.node[point]!.next;
		// Iterate all edges in given node point
		while (temp  != nil)
		{
			self.dfs(&visit, temp!.id);
			// next edge
			temp = temp!.next;
		}
	}
	// Handles the request of printing dfs sequence
	func printDFS(_ point: Int)
	{
		if (self.size <= 0 || point < 0 || point >= self.size)
		{
			return;
		}
		// This is node visitor
		var visit: [Bool] = Array(repeating: false, count: self.size);
		// Start traversal
		self.dfs(&visit, point);
	}
	static func main(_ args: [String])
	{
		// 6 implies the number of nodes in graph
		let g: Graph? = Graph(6);
		g!.addEdge(0, 1);
		g!.addEdge(0, 5);
		g!.addEdge(1, 1);
		g!.addEdge(2, 1);
		g!.addEdge(3, 0);
		g!.addEdge(3, 3);
		g!.addEdge(4, 2);
		g!.addEdge(4, 3);
		g!.addEdge(5, 1);
		g!.printGraph();
		print("\nDFS :", terminator: "");
		g!.printDFS(4);
	}
}
Graph.main([String]());

Output

Adjacency list of vertex 0 : 1  5
Adjacency list of vertex 1 : 1
Adjacency list of vertex 2 : 1
Adjacency list of vertex 3 : 0  3
Adjacency list of vertex 4 : 2  3
Adjacency list of vertex 5 : 1
DFS :  4  2  1  3  0  5

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment