python bfs&dfs

#coding=utf-8


from multiprocessing import Queue
#from queue import queue
adj_list = {
	"A":["B","D"],
	"B":["A","C"],
	"C":["B"],
	"D":["A","E","F"],
	"E":["D","F","G"],
	"F":["D","E","H"],
	"G":["E","H"],
	"H":["G","F"]

}
print (adj_list)

visited= {}
level = {}
parent = {}
bfs_traversal_output=[]
queue = Queue()

for node in adj_list.keys():
	visited[node] = False
	parent[node] = None
	level[node] = -1

s = "A"
visited[s] = True
level[s] = 0
queue.put(s)

while not queue.empty():
	u = queue.get()
	bfs_traversal_output.append(u)

	for v in adj_list[u]:
		if not visited[v]:
			visited[v] = True
			parent[v] = u
			level[v] = level[u]+1
			queue.put(v)

print(bfs_traversal_output)

list 加元素 .append 

queue加元素 .put()

list相减:   一个是list1,list1 = [1, 2, 3, 4, 5]
          一个是list2,list2 = [1, 4, 5]

            list3中包括所有不在list2中出现的list1中的元素。

            list3 = list(set(list1) - set(list2))

#寻找某个点距离原点最近的path
v = "G"
path = []
while v is not None:
	path.append(v)
	v= parent[v]
path.reverse()
print(path)

那dfs呢?

#coding=utf-8

adj_list = {
	"A":["B","C"],
	"B":["D","E"],
	"C":["B","F"],
	"D":[],
	"E":["F"],
	"F":[]

} 
color = {}  # W , G, B
parent ={}
trav_time = {}   #[start ,end]
dfs_traversal_output = []

for node in adj_list.keys():
	color[node] = "w"
	parent[node] = None
	trav_time[node] = [-1,-1]


time = 0

def dfs_util(u):
	global time
	color[u] = "G"
	trav_time[u][0] = time
	dfs_traversal_output.append(u)

	for v in adj_list[u]:
		if color[v] == "W":
			parent[v] = u
			dfs_util(v)
	color[u]=  "B"
	trav_time[u][1] = time
	time +=1 

dfs_util("A")
print(dfs_traversal_output)
 

for node in adj_list.keys():
	print(node," ->",trav_time[node])
	

 

你可能感兴趣的:(BFS,dfs)