常用算法 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。

参考题目:力扣

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Luchang-Li

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值