之前学算法经常不求甚解,懒癌发作不敲代码不实践,到头来自己挖的坑还是得自己填,我会陆续更新代码,本文大量代码来自互联网,能找到出处的我会尽量贴上出处
广度优先搜索、深度优先搜索
class graph():
def __init__(self,*arg,**kwargs):
self.node_neighbors={}
self.visited={}
def add_nodes(self,nodelist):
for node in nodelist:
self.add_node(node)
def add_node(self,node):
if node not in self.node_neighbors.keys:
self.node_neighbors[node]=[]
def add_edge(self,edge):
u,v=edge
if (u not in self.node_neighbors[v]) and (v not in self.node_neighbors[u]):
self.node_neighbors[u].append(v)
if u!=v:
self.node_neighbors[v].append(u)
def depth_first_search(self,root=None):
self.visited={}
order=[]
def dfs(n):
self.visited[n]=True
order.append(n)
for node in self.node_neighbors[n]:
if node not in self.visited:
dps(node)
if root:
dps(root)
for n in self.node_neighbors.keys:
if n not in self.visited:
dps(n)
print(order)
return order
def breadth_first_search(self,root=None):
self.visited={}
order=[]
queue=[]
def bfs():
while(len(queue)>0):
node = queue.pop(0)
self.visited[node]=True
for n in self.node_neighbors[node]:
if not n in self.visited and not n in queue:
order.append(n)
queue.append(n)
if root:
queue.append(root)
order.append(root)
bfs()
for node in self.nodes():
if not node in self.visited:
queue.append(node)
order.append(node)
bfs()
print (order)
return order
if __name__ == '__main__':
g = Graph()
g.add_nodes([i+1 for i in range(8)])
g.add_edge((1, 2))
g.add_edge((1, 3))
g.add_edge((2, 4))
g.add_edge((2, 5))
g.add_edge((4, 8))
g.add_edge((5, 8))
g.add_edge((3, 6))
g.add_edge((3, 7))
g.add_edge((6, 7))
print ("nodes:", g.node_neighbors)
order = g.breadth_first_search(1)
order = g.depth_first_search(1)