目的:

学习《人工智能 一种现代方法》一书,编写广度优先搜索算法。

说明:

书中算法源码:

数据结构:

  • 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 = stateself.parent = parentself.action = actionself.path_cost = path_costdef main():global _city_infoimport_city_info()while True:src_city = input('input src city\n')dst_city = input('input dst city\n')#得到某个result,子节点.state=dst_cityresult = 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的状态从目的地到原点一步步添加到pathwhile True:path.append(result.state)if result.parent is None:breakresult = result.parentsize = 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_infodata = [{'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_infonode = 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. 将当前节点添加至exploredexplored.append(node.state)# 目标测试if node.state == dst_state:return nodeif 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. 遍历当前节点的叶子节点,将叶子节点添加至frontierfor 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行已经定义为0child = 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 Truereturn Falseif __name__ == '__main__':main()

NO.65——人工智能学习:python实现广度优先搜索相关推荐

  1. 使用Python实现广度优先搜索

    图 图模拟一组连接,由节点和边组成,一个节点可能与众多节点直接相连,这些节点被称为邻居. 广度优先搜索 广度优先搜索是一种图算法,主要解决两种问题:        1.从节点A出发,有前往节点B的路径 ...

  2. LQ训练营(C++)学习笔记_广度优先搜索

    这里写目录标题 四.广度优先搜索 1.队列的概念 2.小朋友报数问题 2.1 问题描述 2.2 代码实现 3.广度优先搜索概念 4.走迷宫问题 4.1 问题描述 4.2 代码实现 5.过河卒问题 5. ...

  3. 6.3.1广度优先搜索

    ヾ(≧O≦)"好喜欢你 各位同学大家好,上一节课我们介绍了.各位同学大家好,上一节课我们介绍了有关图的基本操作,那么除了上一节课我们介绍的那些相关基本操作之外,还有一种非常重要的操作,就是有 ...

  4. 人工智能学习:python实现迭代加深的深度优先搜索

    人工智能学习:python实现深度优先搜索算法 本文博客链接:http://blog.csdn.net/jdh99,作者:jdh,转载请注明. 环境: 主机:WIN10 python版本:3.5 开发 ...

  5. AI(人工智能:一种现代的方法)学习之:无信息搜索(uninformed search)算法——广度优先搜索、深度优先搜索、Uniform-cost search

    文章目录 参考 搜索算法 深度优先搜索 depth-first search 性能分析 完整性 complete 最优性 optimal 时间复杂度 空间复杂度 广度优先搜索 breadth-firs ...

  6. 图解算法学习笔记(六):广度优先搜索

    目录 1)图简介 2)图是什么 3)广度优先搜索 4)实现图 5)实现算法 6)小结 本章内容; 学习使用新的数据结构图来建立网络模型: 学习广度优先搜索: 学习有向图和无向图: 学习拓扑排序,这种排 ...

  7. 迷宫问题 深度优先搜索 广度优先搜索 宽度优先搜索【python】

    文章目录 一.实验内容 二.深度优先搜索和广度优先搜索总结 1.深度优先搜索算法 2.广度优先搜索算法 三.实验代码和用于测试的迷宫 1.实验代码 2.测试迷宫 2.1 maze1.txt 2.2 m ...

  8. 《算法图解》学习笔记(六):图和广度优先搜索(附代码)

    欢迎关注WX公众号:[程序员管小亮] python学习之路 - 从入门到精通到大师 文章目录 欢迎关注WX公众号:[程序员管小亮] [python学习之路 - 从入门到精通到大师](https://b ...

  9. 如何学习python+人工智能

    做个自我介绍,我13年考上一所很烂专科民办的学校,学的是生物专业,具体的学校名称我就不说出来献丑了.13年我就辍学了,我在那样的学校,一年学费要1万多,但是根本没有人学习,我实在看不到希望,我就退学了 ...

最新文章

  1. matlab 混合C++编程mex方式初级入门
  2. react-native flatlist 上拉加载onEndReached方法频繁触发的问题
  3. C++运算符重载函数作为类成员函数和友元函数
  4. S - C语言实验——余弦
  5. 1074. Reversing Linked List (25)-PAT甲级真题
  6. WebGL编程指南理论分析之物体层次模型(局部运动)
  7. 高中选的美术将来能考计算机学校吗,北京中考美术考上美术高中以后上考大学一定要考美术专业的大学?好考美术高中...
  8. 大侠学java之继承
  9. 嵌入式Linux进程信息及内存布局
  10. 求最大公约数(辗转相除法)
  11. 软件工程项目学生管理系统
  12. logback 配置 日志
  13. Qt QWidget 软件开发模版
  14. Python 计算两点之间的距离
  15. 计算机桌面 文字大小,电脑屏幕字体怎么调大小_电脑系统字体大小设置方法-win7之家...
  16. android siri声波动画,Waver声波效果开源项目:和 Siri 一起学数学
  17. docker redis安装使用
  18. 使用snap安装mosquitto并且进行初步配置
  19. SDWebImage如何避免复用
  20. conda 清除已经下载的缓冲包

热门文章

  1. 《代码整洁之道》阅读笔记——第12章:迭进
  2. Word控件Spire.Doc更新至最新版v10.7,增强产品稳定性,修复老版本漏洞
  3. STM32F407IGT6与STM32F407ZGT6区别
  4. centos8调整分辨率
  5. mysql怎么定位错误信息_如何快速定位MySQL 的错误日志(Error Log)?
  6. 全球最大同性交友平台骚操作
  7. 苹果七绕过基带激活2020_【快讯:苹果135亿的基带订单,高通疑有诈直接拒绝了;网传索尼移动考虑退出东南亚手机市场;黑客成功获取iPhone XS 权限】...
  8. Mac OS下MAT(Memory Analyzer Tool)安装与启动
  9. 悟空出行携手融创文化梦之城、哈弗品牌,融合战略发布会圆满落幕
  10. 跳槽前如何精准评估自己的身价?