BFS:
graph = {
"A":["B", "C"], # 与A相连的节点是B,C
"B":["A", "C", "D"], # 与B相连的节点是A,C,D
"C":["A", "B", "D", "E"],
"D":["B", "C", "E", "F"],
"E":["C", "D"],
"F":["D"]
}
def visit_node(node):
print(node, "->")
def bfs(graph, start_node):
queue = []
queue.append(start_node)
visited = []
while len(queue) > 0:
cur_node = queue.pop(0)
visit_node(cur_node)
visited.append(cur_node)
sub_nodes = graph[cur_node]
for v in sub_nodes:
if (v not in visited) and (v not in queue):
queue.append(v)
bfs(graph, "A")
这个visited+queue可以看成是个连续的queue。整理思路:加入node到queue,加入node的subnode到queue,再加入subnode的subnode到queue。出queue马上被append到visited。
DFS
仅仅把上面queue换成stack
def dfs(graph, start_node):
stack = []
stack.append(start_node)
visited = []
while len(stack) > 0:
cur_node = stack.pop()
visit_node(cur_node)
visited.append(cur_node)
sub_nodes = graph[cur_node]
for v in sub_nodes:
if (v not in visited) and (v not in stack):
stack.append(v)
参考https://alanwalker.me/2019/04/06/Python%E5%AE%9E%E7%8E%B0BFS-DFS/原作是加入queque和stack的时候访问,这里统一出列队,出栈时访问。
链表反转
思路:
插入一个头结点
每次讲node[0]的next取出插入到head之后,直到所有节点都插入到head。
参考题目:力扣
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
data = [1,2,3,4,5,"NULL"]
raw_list = [ListNode(x) for x in data]
for i in range(len(data) - 1):
raw_list[i].next = raw_list[i+1]
def visite_link(head):
while True:
print(head.val)
if head.val == "NULL":
break
head = head.next
fixed_head = ListNode("HEAD")
fixed_head.next = raw_list[0]
# swap node->next to head
def mov_node(node):
mov_node = node.next
node.next = node.next.next
mov_node.next = fixed_head.next
fixed_head.next = mov_node
visite_link(raw_list[0])
while raw_list[0].next.val != "NULL":
mov_node(raw_list[0])
visite_link(fixed_head)