我希望优化此代码,以便在大型图形中进行横向操作,并遵守此算法运行时的处理时间限制。如果有必要,你有任何线索吗?我可以在这里使用任何python嵌入式优化数据结构吗?人们欢迎每一条线索和知识!
import sys
import collections
class Graph:
def __init__(self, amount_vertice):
self.vertice_list = []
self.amount_vertice = amount_vertice
# buffered previous connect components the origin in index vertex. Each entry contains (dfs and bfs) according to format [dfs, bfs]
self.buffered_connect_component = [[[], []] for node in xrange(amount_vertice)]
self.visited_vertice = [0 for node in xrange(amount_vertice)]
for vertex in xrange(amount_vertice):
line = sys.stdin.readline()
self.vertice_list.append(map(lambda x: int(x), line.split()[2:]))
上面的代码部分显示了根据指定的上下文初始化我的图形数据结构:
def print_dfs(self, origin_vertex, number_query):
path = [origin_vertex]
while path:
next_node = path.pop()
if self.visited_vertice[next_node - 1] != number_query:
self.visited_vertice[next_node - 1] = number_query
self.buffered_connect_component[origin_vertex - 1][0].append(str(next_node))
for candidate_next_node in self.vertice_list[next_node - 1][::-1]:
path.append(candidate_next_node)
上面的函数显示了着名的Deep First Search Graph的Algortihm实现。参数origin_vertex是算法开始运行的顶点,而number_query只是从上下文给出的参数。
def print_bfs(self, origin_vertex, number_query):
path = collections.deque([origin_vertex])
while path:
next_node = path.popleft()
if self.visited_vertice[next_node - 1] != number_query:
self.visited_vertice[next_node - 1] = number_query
self.buffered_connect_component[origin_vertex - 1][1].append(str(next_node))
for candidate_next_node in self.vertice_list[next_node - 1]:
path.append(candidate_next_node)
最后,上面是实现Breath First Search Graph的算法的函数,以及类似于bfs函数的参数。