Skip to main content

Adjacency list representation of directed graph in ruby

Ruby program for Adjacency list representation of directed graph. Here problem description and explanation.

#    Ruby Program for 
#    Directed graph representation using adjacency list
class AjlistNode 
	# Define the accessor and reader of class AjlistNode
	attr_reader :id, :next
	attr_accessor :id, :next
	#  Vertices node key
	def initialize(id) 
		#  Set value of node key
		self.id = id
		self.next = nil
	end

end

class Vertices 
	# Define the accessor and reader of class Vertices
	attr_reader :data, :next, :last
	attr_accessor :data, :next, :last
	def initialize(data) 
		self.data = data
		self.next = nil
		self.last = nil
	end

end

class Graph 
	# Define the accessor and reader of class Graph
	attr_reader :size, :node
	attr_accessor :size, :node
	#  Number of Vertices
	def initialize(size) 
		#  Set value
		self.size = size
		self.node = Array.new(size) {nil}
		self.setData()
	end

	#  Set initial node value
	def setData() 
		if (self.size <= 0) 
			print("\nEmpty Graph\n")
		else
 
			index = 0
			while (index < self.size) 
				#  Set initial node value
				self.node[index] = Vertices.new(index)
				index += 1
			end

		end

	end

	#  Connect two nodes
	def connect(start, last) 
		edge = AjlistNode.new(last)
		if (self.node[start].next == nil) 
			self.node[start].next = edge
		else
 
			#  Add edge at the end
			self.node[start].last.next = edge
		end

		#  Get last edge 
		self.node[start].last = edge
	end

	#   Handling the request of adding new edge
	def addEdge(start, last) 
		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\n")
		end

	end

	def printGraph() 
		if (self.size > 0) 
			index = 0
			#  Print graph ajlist Node value
			while (index < self.size) 
				print("\nAdjacency list of vertex ", index ," :")
				temp = self.node[index].next
				while (temp != nil) 
					#  Display graph node 
					print("  ", self.node[temp.id].data)
					#  visit to next edge
					temp = temp.next
				end

				index += 1
			end

		end

	end

end

def main() 
	#  5 implies the number of nodes in graph
	g = Graph.new(5)
	#  Connect node with an edge
	g.addEdge(0, 1)
	g.addEdge(1, 2)
	g.addEdge(1, 4)
	g.addEdge(2, 0)
	g.addEdge(2, 3)
	g.addEdge(4, 3)
	#  print graph element
	g.printGraph()
end

main()

Output

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




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