##This function will return the edges for an undirected graph####
###Example: when edges = [[1,2],[3,2]]
### this will return
{
1: {'nbr': [2], 'id': 1, 'visited': False},
2: {'nbr': [1, 3], 'id': 2, 'visited': False},
3: {'nbr': [2], 'id': 3, 'visited': False}
}
def createEdges(edges):
E = {}
for y in edges:
for x in edges:
if x[0] not in E:
E[x[0]] = {"id": x[0], "nbr": [x[1]], "visited": False}
elif x[1] not in E:
E[x[1]] = {"id": x[1], "nbr": [x[0]], "visited": False}
elif x[0] in E and x[1] not in E[x[0]]['nbr']:
E[x[0]]['nbr'].append(x[1])
elif x[1] in E and x[0] not in E[x[1]]['nbr']:
E[x[1]]['nbr'].append(x[0])
return E
####A function to explore the a vertex of the graph with edges E
def explore(vertex, E):
if vertex not in E:
return
E[vertex]['ccNum'] = cc
E[vertex]['visited'] = True
for x in E[vertex]['nbr']:
if E[x]['visited'] == False:
explore(x, E)
### this function will set the visited index to true for
### all the connecting points of the vertex
### A function for DFS
def DFS(E):
cc = 1
for x in E:
if E[x]['visited'] == False:
explore(x, E)
cc += 1
在引入" cc"之前,一切都运行良好。保持轨道 总连接子图
它现在抛出错误:虽然定义了cc,但是在DFS下调用了public,它在其范围中定义了cc
答案 0 :(得分:0)
是的,cc
在DFS
的范围内定义,但不会在explore
中显示。您可以将其定义为explore
;
def explore(vertex, E, cc):
并传入值;
. . .
explore(x, E, cc)
. . .
答案 1 :(得分:0)
你需要定义" cc"作为探索的参数或将其定义为全局变量。
cc = 0
def explore(vertex, E):
global cc
if vertex not in E:
return
E[vertex]['ccNum'] = cc
E[vertex]['visited'] = True
for x in E[vertex]['nbr']:
if E[x]['visited'] == False:
explore(x, E)
### this function will set the visited index to true for
### all the connecting points of the vertex
### A function for DFS
def DFS(E):
cc = 1
for x in E:
if E[x]['visited'] == False:
explore(x, E)
cc += 1