我想使用DFS算法,并尝试导入文件。我有一个文件的开头和结尾(如下),但是这里有很多问题
1。查找动态图 2.无法正确打印
class Graph:
file = open("input4.txt","r") #import file here
lines = file.readlines()
#find graph for DFS
start_vertex = []
end_vertex = []
for line in lines:
start_vertex.append(line[0])
end_vertex.append(line[1])
graph = {}
for i in range(len(lines)):
v = start_vertex[i]
if v in graph:
graph[v] |= set([end_vertex[i]])
else:
graph[v] = set([end_vertex[i]])
#dfs code
def dfs(graph, start, visited = None):
if visited is None:
visited = set()
visited.add(start)
print(start)
for next in graph[start] - visited:
dfs(graph, next, visited)
return visited
g=Graph()
#print my file
filename = open('input4.txt', 'r')
for line in filename:
node1, node2, d = line.split()
newnode1=sorted(node1) #sort my node
if node1!="END" and node2!="OF":
print(node1)
g.dfs('S') #here is the problem
我的文件input4.txt
first column is start;second is end; third is weight
S V1 3
S V2 2
V1 V3 1
V1 V4 1
V2 V4 1
V2 V6 2
V3 V5 2
V3 V7 3
V4 V7 2
V5 V9 2
V6 V8 4
V7 V9 5
V7 V10 1
V8 V10 3
V8 T 5
V9 V11 3
V10 V13 3
V11 V12 1
V12 T 2
V13 T 9
但显示:TypeError:“ Graph”对象不可下标 我该怎么办? 谢谢你