NO.65——人工智能學習:python實現廣度優先搜索

目的:

        學習《人工智能 一種現代方法》一書,編寫廣度優先搜索算法。

說明:

        書中算法源碼:

數據結構: 

  • frontier : 邊緣。存儲未擴展的節點。用隊列實現。
  • explored : 探索。存儲已訪問的節點。

流程:

  • 如果邊緣爲空,則返回失敗。操作:EMPTY?(frontier)

  • 否則從邊緣中選擇一個葉子節點。操作:POP(frontier)

  • 將葉子節點的狀態放在探索集

  • 遍歷葉子節點的所有動作

                   每個動作產生子節點
                   如果子節點的狀態不在探索集或者邊緣,則目標測試:通過返回。

                   失敗則放入邊緣。操作:INSERT(child, frontier)
 

 

示例代碼:(參考http://blog.csdn.net/jdh99

# -*- coding: utf-8 -*-
# /usr/bin/python
# 作者:Slash
# 實驗日期:20200119
# Python版本:3.7
# 主題:基於深度優先和寬度優先的搜索算法的簡單實現

import pandas as pd
from pandas import Series, DataFrame

# 城市信息:city1 city2 path_cost
_city_info = None

# 按照路徑消耗進行排序的FIFO,低路徑消耗在前面
_frontier_priority = []


# 節點數據結構
class Node:
    def __init__(self, state, parent, action, path_cost):
        self.state = state
        self.parent = parent
        self.action = action
        self.path_cost = path_cost


def main():
    global _city_info
    import_city_info()
    
    while True:
        src_city = input('input src city\n')
        dst_city = input('input dst city\n')
        #得到某個result,子節點.state=dst_city
        result = breadth_first_search(src_city, dst_city)
        if not result:
            print('from city: %s to city %s search failure' % (src_city, dst_city))
        else:
            print('from city: %s to city %s search success' % (src_city, dst_city))
            path = []
            #這是一個回溯的過程,將result的狀態從目的地到原點一步步添加到path
            while True:
                path.append(result.state)
                if result.parent is None:
                    break
                result = result.parent
            size = len(path)
            for i in range(size):
                if i < size - 1:
                    #print()默認打印一行且後面加換行,end=''意爲末尾不換行
                    print('%s->' % path.pop(), end='')
                else:
                    print(path.pop())


def import_city_info():
    global _city_info
    data = [{'city1': 'Oradea', 'city2': 'Zerind', 'path_cost': 71},
            {'city1': 'Oradea', 'city2': 'Sibiu', 'path_cost': 151},
            {'city1': 'Zerind', 'city2': 'Arad', 'path_cost': 75},
            {'city1': 'Arad', 'city2': 'Sibiu', 'path_cost': 140},
            {'city1': 'Arad', 'city2': 'Timisoara', 'path_cost': 118},
            {'city1': 'Timisoara', 'city2': 'Lugoj', 'path_cost': 111},
            {'city1': 'Lugoj', 'city2': 'Mehadia', 'path_cost': 70},
            {'city1': 'Mehadia', 'city2': 'Drobeta', 'path_cost': 75},
            {'city1': 'Drobeta', 'city2': 'Craiova', 'path_cost': 120},
            {'city1': 'Sibiu', 'city2': 'Fagaras', 'path_cost': 99},
            {'city1': 'Sibiu', 'city2': 'Rimnicu Vilcea', 'path_cost': 80},
            {'city1': 'Rimnicu Vilcea', 'city2': 'Craiova', 'path_cost': 146},
            {'city1': 'Rimnicu Vilcea', 'city2': 'Pitesti', 'path_cost': 97},
            {'city1': 'Craiova', 'city2': 'Pitesti', 'path_cost': 138},
            {'city1': 'Fagaras', 'city2': 'Bucharest', 'path_cost': 211},
            {'city1': 'Pitesti', 'city2': 'Bucharest', 'path_cost': 101},
            {'city1': 'Bucharest', 'city2': 'Giurgiu', 'path_cost': 90},
            {'city1': 'Bucharest', 'city2': 'Urziceni', 'path_cost': 85},
            {'city1': 'Urziceni', 'city2': 'Vaslui', 'path_cost': 142},
            {'city1': 'Urziceni', 'city2': 'Hirsova', 'path_cost': 98},
            {'city1': 'Neamt', 'city2': 'Iasi', 'path_cost': 87},
            {'city1': 'Iasi', 'city2': 'Vaslui', 'path_cost': 92},
            {'city1': 'Hirsova', 'city2': 'Eforie', 'path_cost': 86}]
            
    _city_info = DataFrame(data, columns=['city1', 'city2', 'path_cost'])
# print(_city_info)


def breadth_first_search(src_state, dst_state):
    global _city_info
    
    node = Node(src_state, None, None, 0)
    # 1. 將起始點放入frontier列表
    frontier = [node]
    # 2. 建立一個explored,存放已訪問的節點
    explored = []

    while True:
        if len(frontier) == 0:
            return False
        # 3. 將列表中的隊首彈出,這樣符合隊列先進先出的特性
        node = frontier.pop(0)  #相當於popleft()
        # 4. 將當前節點添加至explored
        explored.append(node.state)
        # 目標測試
        if node.state == dst_state:
            return node
        if node.parent is not None:
            print('deal node:state:%s\tparent state:%s\tpath cost:%d' % (node.state, node.parent.state, node.path_cost))
        else:
            print('deal node:state:%s\tparent state:%s\tpath cost:%d' % (node.state, None, node.path_cost))
        
        # 5. 遍歷當前節點的葉子節點,將葉子節點添加至frontier
        for i in range(len(_city_info)):
            dst_city = ''
            if _city_info['city1'][i] == node.state:
                dst_city = _city_info['city2'][i]
            elif _city_info['city2'][i] == node.state:
                dst_city = _city_info['city1'][i]
            if dst_city == '':
                continue
            #將dst_city定義爲葉子節點,node爲父節點,node.path_cost在87行已經定義爲0
            child = Node(dst_city, node, 'go', node.path_cost + _city_info['path_cost'][i])
            print('\tchild node:state:%s path cost:%d' % (child.state, child.path_cost))
            if child.state not in explored and not is_node_in_frontier(frontier, child):
                frontier.append(child)
                print('\t\t add child to child')


def is_node_in_frontier(frontier, node):
    for x in frontier:
        if node.state == x.state:
            return True
    return False


if __name__ == '__main__':
    main()

 

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