leetcode常用算法 BFS DFS 廣度,深度優先搜索

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。

參考題目:https://leetcode-cn.com/problems/reverse-linked-list/

# 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)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章