找到最短路径的算法

时间:2018-05-14 16:58:51

标签: json python-3.x

在我自己写的JSON文件中,我保持城市间的神经和真实的距离。然后我尝试通过从这个JSON文件中提取数据,找到ANKARA和GAZIANTEP之间用A *算法的最短路径。但是我写的代码总是留在安卡拉下一个最近的城市之后。

这就是为什么while循环,无限循环。

我的代码:

import json as JS
import operator

def main():
    with open('provinces.json', encoding='utf-8') as f:
        tree = JS.load(f)

    path = []
    Astar(tree, path)

def Astar(tree, path):

    province_of_cost = {}
    counter = 0
    visited_cost = 0
    goal_province = ''

    while goal_province != 'Gaziantep':
        for province in tree['children']:
            cost = 0
            cost = visited_cost + province['heuristic'] + province['distance']
            province_of_cost[cost] = tree['children'][counter]
            counter = counter + 1

        counter = 0
        sorted_costs = sorted(province_of_cost.items(), key=operator.itemgetter(0))
        path.append(tree['name'])
        tree = sorted_costs[0][1]

        visited_cost = visited_cost + tree['distance']
        goal_province = tree['name']

    print(path)

if __name__ == '__main__':
    main()

我想要的输出:

安卡拉 - > Kırıkkale - > Kırşehir - > Nevşehir - >开塞利 - > Kahramanmaraş - >加齐安特普

此代码的输出:

安卡拉 - > Kırıkkale - > Kırıkkale - >Kırıkkale - > ...

0 个答案:

没有答案