输出无向图内任意长度的环(python)

功能:统计并输出无向图内指定长度的环路

# Python Program to count
# cycles of length n
# in a given graph.

# Number of vertices
V = 5


def DFS(graph, marked, n, vert, start, count, path):
    # mark the vertex vert as visited
    marked[vert] = True

    # if the path of length (n-1) is found
    if n == 0:

        # mark vert as un-visited to make
        # it usable again.
        marked[vert] = False

        # Check if vertex vert can end with
        # vertex start
        if graph[vert][start] == 1:
            count = count + 1
            path.append(start)
            print(path)
            path.pop()

            return count
        else:
            return count

    # For searching every possible path of
    # length (n-1)
    for i in range(V):
        if marked[i] == False and graph[vert][i] == 1:
            # DFS for searching path by decreasing
            # length by 1
            path.append(i)
            count = DFS(graph, marked, n - 1, i, start, count, path)
            for node in path:
                if not marked[node] == True:
                    path.remove(node)

    # marking vert as unvisited to make it
    # usable again.
    marked[vert] = False
    return count


# Counts cycles of length
# N in an undirected
# and connected graph.
def countCycles(graph, n):
    # all vertex are marked un-visited intially.
    marked = [False] * V

    # Searching for cycle by using v-n+1 vertices
    count = 0
    for i in range(V - (n - 1)):
        path = []
        path.append(i)
        count = DFS(graph, marked, n - 1, i, i, count, path)

        # ith vertex is marked as visited and
        # will not be visited again.
        marked[i] = True

    return int(count / 2)


# main :
graph = [[0, 1, 0, 1, 0],
         [1, 0, 1, 0, 1],
         [0, 1, 0, 1, 0],
         [1, 0, 1, 0, 1],
         [0, 1, 0, 1, 0]]

n = 4
print("Total cycles of length ", n, " are ", countCycles(graph, n))

# this code is contributed by Shivani Ghughtyal

输出

[0, 1, 2, 3, 0]
[0, 1, 4, 3, 0]
[0, 3, 2, 1, 0]
[0, 3, 4, 1, 0]
[1, 2, 3, 4, 1]
[1, 4, 3, 2, 1]
Total cycles of length  4  are  3

由于相同路径会被for循环计两次,故输出的路径有重复路径,count需要除2

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值