[英]Trying to implement breadth first search from text file in python
So I was able to implement breadth first search like this.所以我能够像这样实现广度优先搜索。 But Now I am trying to implement breadth first search from a text file that looks like this.但是现在我正在尝试从一个看起来像这样的文本文件中实现广度优先搜索。
Textfile:文本文件:
1,1
1,1
4,1
4,5
5,1
This is the code:这是代码:
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def BFS(self, s):
visited = [False] * (max(self.graph) + 1)
queue = []
queue.append(s)
visited[s] = True
while queue:
s = queue.pop(0)
print (s, end = " ")
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
Output: 2 0 3 1 Output:2 0 3 1
This is how I adjusted the text file, but i still cant figure out how to implement it:这就是我调整文本文件的方式,但我仍然无法弄清楚如何实现它:
data = open("ajd.txt", "r")
list_of_lists = []
for line in data.readlines():
stripped_line = line.strip('\n')
line_list = list(map(int, stripped_line.split(',')))
list_of_lists.append(line_list)
data.close()
print(list_of_lists)
adjLists = list_of_lists
def convert(a):
adjList = defaultdict(list)
for i in range(len(a)):
for j in range(len(a[i])):
if a[i][j]== 1:
adjList[i].append(j)
return adjList
Output: [[1, 1], [1, 1], [4, 1], [4, 5], [5, 1]] Output: [[1, 1], [1, 1], [4, 1], [4, 5], [5, 1]]
Hi I think this is what you want, but I don't know if it's right.嗨,我认为这是您想要的,但我不知道它是否正确。
There was no exact description of the ajd.txt
file, so I put a value arbitrarily.没有对ajd.txt
文件的确切描述,所以我随意放了一个值。 Maybe adj.txt
has an explanation of the starting value
.也许adj.txt
对starting value
有解释。 If you tell me that part, I can give you the exact details.如果你告诉我那部分,我可以给你确切的细节。
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def BFS(self, s):
visited = [False] * (max(self.graph) + 1)
queue = []
queue.append(s)
visited[s] = True
while queue:
s = queue.pop(0)
print(s, end=" ")
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
g.BFS(2)
def convert(a):
adjList = defaultdict(list)
for i in range(len(a)):
for j in range(len(a[i])):
if a[i][j] == 1:
adjList[i].append(j)
return adjList
print('')
data = open("ajd.txt", "r")
list_of_lists = []
for line in data.readlines():
stripped_line = line.strip('\n')
line_list = list(map(int, stripped_line.split(',')))
list_of_lists.append(line_list)
data.close()
print(list_of_lists)
adjLists = list_of_lists
new_g = Graph()
for line in list_of_lists:
new_g.addEdge(line[0], line[1])
# I'm not sure the starting point, so i set it 3 randomly
new_g.BFS(3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.