그래프 구현에서 모든 주기 찾기 (Find all cycles in a graph implementation)


문제 설명

그래프 구현에서 모든 주기 찾기 (Find all cycles in a graph implementation)

여기에서 그래프의 모든 주기를 찾는 간단한 알고리즘을 찾았습니다. 사이클도 인쇄해야 합니다. 이 알고리즘으로 가능합니까? 아래의 코드를 찾아주세요.

정확하게 사이클 수를 구하고 있습니다!

node1, node2는 정수입니다. 방문은 사전입니다

6
def dfs(self,node1, node2):
    if self.visited[node2]:
        if(node1 == node2):
            self.count += 1
            print node2
        return

    self.visited[node2] = True

    for x in self.adj_lst[node2‑1]:
        self.dfs(node1, x)

    self.visited[node2] = False

def allCycles(self):
    self.count = 0
    for x in self.VList:
        self.dfs(x.num, x.num)
        self.visited[x.num] = True

    print "Number of cycles: "+str(self.count)

참조 솔루션

방법 1:

Yes of course you can construct the path, now you can do it recursively but I'm not a great fan of managing temporary state in the class.

Here's a simple implementations using a stack:

def dfs(graph, start, end):
    fringe = [(start, [])]
    while fringe:
        state, path = fringe.pop()
        if path and state == end:
            yield path
            continue
        for next_state in graph[state]:
            if next_state in path:
                continue
            fringe.append((next_state, path+[next_state]))

>>> graph = { 1: [2, 3, 5], 2: [1], 3: [1], 4: [2], 5: [2] }
>>> cycles = [[node]+path  for node in graph for path in dfs(graph, node, node)]
>>> len(cycles)
7
>>> cycles
[[1, 5, 2, 1], [1, 3, 1], [1, 2, 1], [2, 1, 5, 2], [2, 1, 2], [3, 1, 3], [5, 2, 1, 5]]

Note: 4 cannot get back to itself.

방법 2:

Yes, it's possible. You can just store the parent of each vertex and then iterate over the array of parents (until you reach the start vertex) to print the cycle when you find one.

(by Kalyan ChavaliAChampionkraskevich)

참조 문서

  1. Find all cycles in a graph implementation (CC BY‑SA 2.5/3.0/4.0)

#directed-graph #Python #graph #algorithm






관련 질문

다른 유형의 멤버가 있는 두 개의 구조체를 선언하는 방법은 무엇입니까? (How to declare two structs which have members of the others type?)

깊이 우선 그래프 검색 트리의 백 에지 (Back Edges in a depth first graph search tree)

각 노드에 최대 하나의 아웃바운드 에지가 있는 완전 연결 방향 그래프를 무엇이라고 합니까? (What do you call a fully connected directed graph where each node has at most one outbound edge?)

Floyd-Warshall 알고리즘 (Floyd-Warshall algorithm)

도트 그래픽의 일부 라인을 평행하게 만드는 방법은 무엇입니까? (How to make some lines of a dot graphic parallel?)

그래프 구현에서 모든 주기 찾기 (Find all cycles in a graph implementation)

반전이 있는 TSP (TSP with a twist)

C++ 방향 그래프 깊이 우선 탐색 (c++ directed graph depth first search)

Python에서 레이블이 지정된 병렬 모서리/꼭짓점을 사용하여 방향 그래프 생성 (Generating Directed Graph With Parallel Labelled Edges/Vertices in Python)

개체 배열을 설정하는 동안 FindBug 오류 '변경 가능한 개체에 대한 참조를 통합하여 내부 표현을 노출할 수 있음'을 수정하는 방법은 무엇입니까? (How to Fix FindBug error 'May expose internal representation by incorporating reference to mutable object' while setting Array of Objects?)

그래프 직렬화 (Graph serialization)

유향 그래프를 저장/액세스하는 가장 좋은 방법 (Best Way to Store/Access a Directed Graph)







코멘트