《算法图解》的一些算法笔记

这本书个人觉得它的重点还是在于广度优先搜索算法、Dijkstra算法、动态规划—(背包问题、最长公共子串、最长公共子串序列)、贪婪算法、NP问题的讲解。
按照书上的代码及自己的一些思路,把代码复现了一遍。作篇记录,方便后期自己学习的时候查阅。
《算法图解》的一些算法笔记
BFS算法:

#!/user/bin/python3
# -*- coding:utf-8 -*-
#@Date      :2018/10/24  19:06
#@Author    :Syler([email protected])
from queue import Queue
graph = {}
que = Queue()
#第一层
graph["you"] = ["BOB", "CLAIRE", "ALICE"]
#第二层
graph["CLAIRE"] = ["THOM", "JONNY"]
graph["ALICE"] = ["PEGGY"]
graph["BOB"] = ["ANUJ", "PEGGY"]
#第三层
graph["THOM"] = []
graph["JONNY"] = []
graph["ANUJ"] = []
graph["PEGGY"] = []

que.put(graph["you"])
processed = []

record = []

while not que.empty():
    node = que.get()
    need_node = node[0]
    tmp_node = node[1:]
    if need_node not in processed:
        if need_node == "THOM":
            print("找到了!")
            break
        else:
            tmp_node.extend(graph[need_node])
            que.put(tmp_node)
            processed.append(need_node)

d = []
def re(ke):
    # 现在的层数是第一层:
    if ke == 'you':
        d.append(ke)
        return 1#这层的键
    else:
        #把这一次的ke添加到一个列表
        d.append(ke)
        for k,v in graph.items():
            if ke in v:
                a = k
                break
        return re(a)
#如果找到了所需要的人物,那么如何确定它的关系图,即从you到目标人物的最短度量
re("PEGGY")
d.reverse()
print(d)

《算法图解》的一些算法笔记
《算法图解》的一些算法笔记
Dijkstra算法:

#!/user/bin/python3
# -*- coding:utf-8 -*-
#@Date      :2018/10/24  20:33
#@Author    :Syler([email protected])

def find_lowest_cost_node(costs):
    lowest_cost = float("inf")
    lowest_cost_node = None
    for node in costs:
        cost = costs[node]
        if cost < lowest_cost and node not in processed:
            lowest_cost = cost
            lowest_cost_node = node
    return lowest_cost_node

graph = {}
graph["start"] = {}
graph["start"]["A"] = 6
graph["start"]["B"] = 2
graph["A"] = {}
graph["A"]["finally"] = 1
graph["B"] = {}
graph["B"]["A"] = 3
graph["B"]["finally"] = 5
graph["finally"] = {}

infinity = float("inf")
costs = {}
costs["A"] = 6
costs["B"] = 2
costs["finally"] = infinity

parents = {}
parents["A"] = "start"
parents["B"] = "start"
parents["finally"] = None

processed = []

node = find_lowest_cost_node(costs)
while node is not None:
    cost = costs[node]
    neighborhoods = graph[node]
    for n in neighborhoods.keys():
        new_cost = cost + neighborhoods[n]
        if costs[n] > new_cost:
            costs[n] = new_cost
            parents[n] = node
    processed.append(node)
    node = find_lowest_cost_node(costs)

print(processed)

暂时先记下这些笔记,后期需要的时候,不断扩充吧。