Skip to main content

Find maximum weight cycle in an undirected graph in swift

Swift program for Find maximum weight cycle in an undirected graph. Here more information.

import Foundation
/*
    Swift 4 program for 
    Maximum weight cycle in an undirected graph
*/
class AjlistNode
{
	// Vertices node key
	var id: Int;
	var weight: Int;
	var next: AjlistNode? ;
	init(_ id: Int, _ weight: Int)
	{
		// Set value of node key
		self.id = id;
		self.weight = weight;
		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 result: Int;
	var node: [Vertices? ];
	init(_ size: Int)
	{
		// Set value
		self.size = size;
		self.result = 0;
		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;
			}
		}
	}
	func connection(_ start: Int, _ last: Int, _ weight: Int)
	{
		// Safe connection
		let edge: AjlistNode? = AjlistNode(last, weight);
		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, _ weight: Int)
	{
		if (start >= 0 && start < self.size && 
            last >= 0 && last < self.size)
		{
			self.connection(start, last, weight);
			if (start == last)
			{
				return;
			}
			self.connection(last, start, weight);
		}
		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 edge: AjlistNode? = self.node[index]!.next;
				while (edge  != nil)
				{
					// Display graph node 
					print("  " + String(self.node[edge!.id]!.data) + 
                          "[" + String(edge!.weight) + "]", terminator: "");
					// Visit to next edge
					edge = edge!.next;
				}
				index += 1;
			}
		}
	}
	func maximumCycle(_ start: Int, _ last: Int, 
                      _ visit: inout[Bool], _ sum: Int)
	{
		if (start >= self.size || last >= self.size || 
            start < 0 || last < 0 || self.size <= 0)
		{
			return;
		}
		if (visit[start] == true)
		{
			if (start == last && sum > self.result)
			{
				// When find a new max weight cycle
				self.result = sum;
			}
			return;
		}
		// Here modified  the value of visited node
		visit[start] = true;
		// This is used to iterate nodes edges
		var edge: AjlistNode? = self.node[start]!.next;
		while (edge  != nil)
		{
			self.maximumCycle(edge!.id, last, 
                              &visit, sum + (edge!.weight));
			// Visit to next edge
			edge = edge!.next;
		}
		// Reset the value of visited node status
		visit[start] = false;
	}
	func maxWeightCycle()
	{
		if (self.size <= 0)
		{
			// Empty graph
			return;
		}
		// Auxiliary space which is used to store 
		// information about visited node
		var visit: [Bool] = Array(repeating: false, count: self.size);
		self.result = Int.min;
		var i: Int = 0;
		while (i < self.size)
		{
			// Check cycle of node i to i
			// Here initial cycle weight is zero
			self.maximumCycle(i, i, &visit, 0);
			i += 1;
		}
		if (self.result == Int.min)
		{
			print("\nMax weight cycle : None ");
		}
		else
		{
			print("\nMax weight cycle : " + String(self.result));
		}
	}
	static func main(_ args: [String])
	{
		// 6 implies the number of nodes in graph
		let g: Graph = Graph(6);
		// Connect node with an edge
		// First and second parameter indicate node
		// Last parameter is indicate weight
		g.addEdge(0, 1, 3);
		g.addEdge(0, 3, -3);
		g.addEdge(0, 4, 7);
		g.addEdge(0, 5, 1);
		g.addEdge(1, 2, 11);
		g.addEdge(1, 4, 8);
		g.addEdge(1, 5, 0);
		g.addEdge(2, 3, 1);
		g.addEdge(2, 5, 5);
		g.addEdge(3, 4, 2);
		g.addEdge(4, 5, 8);
		// Print graph element
		g.printGraph();
		// Test
		g.maxWeightCycle();
	}
}
Graph.main([String]());

Output

Adjacency list of vertex 0 :  1[3]  3[-3]  4[7]  5[1]
Adjacency list of vertex 1 :  0[3]  2[11]  4[8]  5[0]
Adjacency list of vertex 2 :  1[11]  3[1]  5[5]
Adjacency list of vertex 3 :  0[-3]  2[1]  4[2]
Adjacency list of vertex 4 :  0[7]  1[8]  3[2]  5[8]
Adjacency list of vertex 5 :  0[1]  1[0]  2[5]  4[8]
Max weight cycle : 34




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