Qo'shni matritsa ko'rinishida siz tugunning qo'shnilarini aniqlash uchun barcha tugunlar bo'ylab takrorlashingiz kerak bo'ladi.
a b c d e
a 1 1 - - -
b - - 1 - -
c - - - 1 -
d - 1 1 - -
Qo'shnilik ro'yxati cheklangan grafikni ifodalash uchun ishlatiladi. Qo'shnilar ro'yxatini ko'rsatish tugunning qo'shnilari orqali osongina takrorlash imkonini beradi. Ro'yxatdagi har bir indeks cho'qqini ifodalaydi va bu indeks bilan bog'langan har bir tugun uning qo'shni cho'qqilarini ifodalaydi.
1 a -> { a b }
2 b -> { c }
3 c -> { d }
4 d -> { b c }
Grafikni amalga oshirish talablari juda oddiy. Bizga ikkita ma'lumot elementi kerak bo'ladi: grafikdagi uchlarning umumiy soni va qo'shni cho'qqilarni saqlash uchun ro'yxat . Bundan tashqari, qirralarning yoki qirralarning to'plamini qo'shish usuli kerak.
class AdjNode:
"""
A class to represent the adjacency list of the node
"""
def __init__(self, data):
"""
Constructor
:param data : vertex
"""
self.vertex = data
self.next = None
class Graph:
"""
Graph Class ADT
"""
def __init__(self, vertices):
"""
Constructor
:param vertices : Total vertices in a graph
"""
self.V = vertices
self.graph = [None] * self.V
# Function to add an edge in an undirected graph
def add_edge(self, source, destination):
"""
add edge
:param source: Source Vertex
:param destination: Destination Vertex
"""
# Adding the node to the source node
node = AdjNode(destination)
node.next = self.graph[source]
self.graph[source] = node
# Adding the source node to the destination if undirected graph
# Intentionally commented the lines
#node = AdjNode(source)
#node.next = self.graph[destination]
#self.graph[destination] = node
def print_graph(self):
"""
A function to print a graph
"""
for i in range(self.V):
print("Adjacency list of vertex {}\n head".format(i), end="")
temp = self.graph[i]
while temp:
print(" -> {}".format(temp.vertex), end="")
temp = temp.next
print(" \n")
# Main program
if __name__ == "__main__":
V = 5 # Total vertices
g = Graph(V)
g.add_edge(0, 1)
g.add_edge(0, 4)
g.add_edge(1, 2)
g.add_edge(1, 3)
g.add_edge(1, 4)
g.add_edge(2, 3)
g.add_edge(3, 4)
g.print_graph()
Yuqoridagi misolda biz Python grafik sinfini ko'ramiz . Biz grafik sinfimizning poydevorini qo'ydik. V o'zgaruvchisi umumiy sonni ko'rsatadigan butun sonni o'z ichiga oladi.
Dostları ilə paylaş: |