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

人工智能学习:python实现深度优先搜索算法



本文博客链接:http://blog.csdn.net/jdh99,作者:jdh,转载请注明.

 

环境:

主机:WIN10

python版本:3.5

开发环境:pyCharm


说明:

源码中的罗马尼亚城市地图与《人工智能学习:python实现宽度优先搜索算法》中的地图一致。

可以对比《人工智能学习:python实现深度优先搜索算法》。


迭代加深的深度优先搜索原理和伪代码:

人工智能学习:python实现迭代加深的深度优先搜索_第1张图片

 

 

算法流程分析:

流程:

  • 深度逐渐加深,调用深度优先搜索进行搜索

 

 

算法性能分析:

  • 有些状态被重复生成。但代价并非那么大,因为绝大多数节点都在底层,所以上层节点重复生成多次影响不大。生成的节点总数:


 

  • 时间复杂度:


 

与宽度优先搜索想比,重复生成节点代价不大,举例:

人工智能学习:python实现迭代加深的深度优先搜索_第2张图片

 

 

 

人工智能学习:python实现迭代加深的深度优先搜索_第3张图片

源码:

import pandas as pd
from pandas import Series, DataFrame

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

# 已探索集合
_explored = []


# 节点数据结构
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, _explored
    import_city_info()

    while True:
        src_city = input('input src city\n')
        dst_city = input('input dst city\n')
        result = iterative_deepening_search(src_city, dst_city)
        if result == "failure" or result == "cutoff":
            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 = []
            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('%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 iterative_deepening_search(src_state, dst_state):
    for i in range(100):
        result = depth_limited_search(src_state, dst_state, i)
        if result != "failure" and result != "cutoff":
            return result
    return "cutoff"


def depth_limited_search(src_state, dst_state, limit):
    global _explored
    _explored = []
    node = Node(src_state, None, None, 0)
    return recursive_dls(node, dst_state, limit)


def recursive_dls(node, dst_state, limit):
    """

    :param node:
    :param dst_state:
    :param limit:
    :return: "failure":失败."cutoff":被截至.node:成功
    """
    global _city_info, _explored

    if node.parent is not None:
        print('node state:%s parent state:%s' % (node.state, node.parent.state))
    else:
        print('node state:%s parent state:%s' % (node.state, None))
    _explored.append(node.state)

    # 目标测试
    if node.state == dst_state:
        print('this node is goal!')
        return node
    elif limit == 0:
        print('this node is cutoff!')
        return "cutoff"
    else:
        cutoff_occurred = False

        # 遍历子节点
        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
            child = Node(dst_city, node, 'go', node.path_cost + _city_info['path_cost'][i])
            # 过滤已探索的点
            if child.state in _explored:
                continue
            print('child node:state:%s path cost:%d' % (child.state, child.path_cost))

            result = recursive_dls(child, dst_state, limit - 1)
            if result == "cutoff":
                cutoff_occurred = True
                print('search failure, child state: %s parent state: %s limit cutoff' %
                      (child.state, child.parent.state))
            elif result != "failure":
                print('search success')
                return result
        if cutoff_occurred:
            return "cutoff"
        else:
            return "failure"


if __name__ == '__main__':
    main()


测试:从Zerind导航到Urziceni:

input src city
Zerind
input dst city
Urziceni
node state:Zerind parent state:None
this node iscutoff!
node state:Zerind parent state:None
child node:state:Oradea path cost:71
node state:Oradea parent state:Zerind
this node iscutoff!
search failure, child state: Oradea parent state: Zerind limitcutoff
child node:state:Arad path cost:75
node state:Arad parent state:Zerind
this node iscutoff!
search failure, child state: Arad parent state: Zerind limit cutoff
node state:Zerind parent state:None
child node:state:Oradea path cost:71
node state:Oradea parent state:Zerind
child node:state:Sibiu path cost:222
node state:Sibiu parent state:Oradea
this node iscutoff!
search failure, child state: Sibiu parent state: Oradea limitcutoff
search failure, child state: Oradea parent state: Zerind limitcutoff
child node:state:Arad path cost:75
node state:Arad parent state:Zerind
child node:state:Timisoara path cost:193
node state:Timisoara parent state:Arad
this node iscutoff!
search failure, child state: Timisoara parent state: Arad limitcutoff
search failure, child state: Arad parent state: Zerind limit cutoff
node state:Zerind parent state:None
child node:state:Oradea path cost:71
node state:Oradea parent state:Zerind
child node:state:Sibiu path cost:222
node state:Sibiu parent state:Oradea
child node:state:Arad path cost:362
node state:Arad parent state:Sibiu
this node iscutoff!
search failure, child state: Arad parent state: Sibiu limit cutoff
child node:state:Fagaras path cost:321
node state:Fagaras parent state:Sibiu
this node iscutoff!
search failure, child state: Fagaras parent state: Sibiu limitcutoff
child node:state:Rimnicu Vilcea path cost:302
node state:Rimnicu Vilcea parent state:Sibiu
this node iscutoff!
search failure, child state: Rimnicu Vilcea parent state: Sibiu limitcutoff
search failure, child state: Sibiu parent state: Oradea limitcutoff
search failure, child state: Oradea parent state: Zerind limit cutoff
node state:Zerind parent state:None
child node:state:Oradea path cost:71
node state:Oradea parent state:Zerind
child node:state:Sibiu path cost:222
node state:Sibiu parent state:Oradea
child node:state:Arad path cost:362
node state:Arad parent state:Sibiu
child node:state:Timisoara path cost:480
node state:Timisoara parent state:Arad
this node iscutoff!
search failure, child state: Timisoara parent state: Arad limitcutoff
search failure, child state: Arad parent state: Sibiu limit cutoff
child node:state:Fagaras path cost:321
node state:Fagaras parent state:Sibiu
child node:state:Bucharest path cost:532
node state:Bucharest parent state:Fagaras
this node iscutoff!
search failure, child state: Bucharest parent state: Fagaras limitcutoff
search failure, child state: Fagaras parent state: Sibiu limitcutoff
child node:state:Rimnicu Vilcea path cost:302
node state:Rimnicu Vilcea parent state:Sibiu
child node:state:Craiova path cost:448
node state:Craiova parent state:Rimnicu Vilcea
this node iscutoff!
search failure, child state: Craiova parent state: Rimnicu Vilcea limitcutoff
child node:state:Pitesti path cost:399
node state:Pitesti parent state:Rimnicu Vilcea
this node iscutoff!
search failure, child state: Pitesti parent state: Rimnicu Vilcea limitcutoff
search failure, child state: Rimnicu Vilcea parent state: Sibiu limitcutoff
search failure, child state: Sibiu parent state: Oradea limit cutoff
search failure, child state: Oradea parent state: Zerind limit cutoff
node state:Zerind parent state:None
child node:state:Oradea path cost:71
node state:Oradea parent state:Zerind
child node:state:Sibiu path cost:222
node state:Sibiu parent state:Oradea
child node:state:Arad path cost:362
node state:Arad parent state:Sibiu
child node:state:Timisoara path cost:480
node state:Timisoara parent state:Arad
child node:state:Lugoj path cost:591
node state:Lugoj parent state:Timisoara
this node iscutoff!
search failure, child state: Lugoj parent state: Timisoara limitcutoff
search failure, child state: Timisoara parent state: Arad limitcutoff
search failure, child state: Arad parent state: Sibiu limit cutoff
child node:state:Fagaras path cost:321
node state:Fagaras parent state:Sibiu
child node:state:Bucharest path cost:532
node state:Bucharest parent state:Fagaras
child node:state:Pitesti path cost:633
node state:Pitesti parent state:Bucharest
this node iscutoff!
search failure, child state: Pitesti parent state: Bucharest limitcutoff
child node:state:Giurgiu path cost:622
node state:Giurgiu parent state:Bucharest
this node iscutoff!
search failure, child state: Giurgiu parent state: Bucharest limitcutoff
child node:state:Urziceni path cost:617
node state:Urziceni parent state:Bucharest
this node isgoal!
search success
search success
search success
search success
search success
from city: Zerind to city Urziceni searchsuccess
Zerind->Oradea->Sibiu->Fagaras->Bucharest->Urziceni


可以看出,与深度优先搜索算法相比,本算法可以找出更优深度的路径。


你可能感兴趣的:(人工智能)