트리의 모든 노드의 합을 구해야 할 때 클래스를 생성하고 루트 노드를 설정하고 트리에 요소를 추가하고 특정 요소를 검색하고 트리의 요소를 추가하는 메소드를 포함합니다. 합계 등을 찾습니다. 이러한 메서드에 액세스하고 사용하기 위해 클래스의 인스턴스를 만들 수 있습니다.
아래는 동일한 데모입니다 -
예시
class Graph_structure:
def __init__(self, V):
self.V = V
self.adj = [[] for i in range(V)]
def DFS_Utility(self, temp, v, visited):
visited[v] = True
temp.append(v)
for i in self.adj[v]:
if visited[i] == False:
temp = self.DFS_Utility(temp, i, visited)
return temp
def add_edge(self, v, w):
self.adj[v].append(w)
self.adj[w].append(v)
def find_connected_components(self):
visited = []
connected_comp = []
for i in range(self.V):
visited.append(False)
for v in range(self.V):
if visited[v] == False:
temp = []
connected_comp.append(self.DFS_Utility(temp, v, visited))
return connected_comp
my_instance = Graph_structure(6)
my_instance.add_edge(1, 0)
my_instance.add_edge(2, 3)
my_instance.add_edge(3, 4)
my_instance.add_edge(5, 0)
print("There are 6 edges. They are : ")
print("1-->0")
print("2-->3")
print("3-->4")
print("5-->0")
connected_comp = my_instance.find_connected_components()
print("The connected components are...")
print(connected_comp) 출력
There are 6 edges. They are : 1-->0 2-->3 3-->4 5-->0 The connected components are... [[0, 1, 5], [2, 3, 4]]
설명
-
'_init_' 메서드로 'Graph_structure'라는 클래스가 정의됩니다.
-
그래프의 요소에 대해 깊이 우선 탐색을 수행하는 데 도움이 되는 'DFS_Utility'라는 메서드가 정의되어 있습니다.
-
그래프에 노드를 추가하는 데 도움이 되는 'add_edge'라는 또 다른 메서드가 정의되어 있습니다.
-
특정 노드에 연결된 노드를 결정하는 데 도움이 되는 'find_connected_components'라는 또 다른 메서드가 정의되어 있습니다.
-
'Graph_structure'의 인스턴스가 생성됩니다.
-
요소는 'add_edge' 메소드를 사용하여 추가됩니다.
-
콘솔에 표시됩니다.
-
'find_connected_components'가 호출되고 출력이 콘솔에 표시됩니다.