求无向有环图的最短路径python

最近在做项目的过程中遇到了这样的问题:在有15个节点的无向有环图中需要求出任意 a,b 两点间的最短距离路径。
这里写图片描述
我的做法是先将图转换为 邻接矩阵 的形式存储呈二维数组相连节点为0不相连为-1

[[ 0  0  0  0 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1]
 [ 0  0 -1 -1  0 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1]
 [ 0 -1  0 -1  0  0 -1 -1 -1 -1 -1 -1 -1 -1 -1]
 [ 0 -1 -1  0 -1  0 -1 -1 -1  0 -1 -1  0 -1 -1]
 [-1  0  0 -1  0 -1  0 -1 -1 -1 -1 -1 -1 -1 -1]
 [-1 -1  0  0 -1  0  0  0  0 -1 -1 -1 -1 -1 -1]
 [-1 -1 -1 -1  0  0  0 -1 -1 -1 -1 -1 -1 -1 -1]
 [-1 -1 -1 -1 -1  0 -1  0 -1 -1  0 -1 -1 -1 -1]
 [-1 -1 -1 -1 -1  0 -1 -1  0  0 -1 -1 -1 -1  0]
 [-1 -1 -1  0 -1 -1 -1 -1  0  0 -1 -1 -1  0 -1]
 [-1 -1 -1 -1 -1 -1 -1  0 -1 -1  0 -1 -1  0 -1]
 [-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1  1  0  0  0]
 [-1 -1 -1  0 -1 -1 -1 -1 -1 -1 -1  0  1 -1 -1]
 [-1 -1 -1 -1 -1 -1 -1 -1 -1  0  0  0 -1  0 -1]
 [-1 -1 -1 -1 -1 -1 -1 -1  0 -1 -1  0 -1 -1  0]]

然后根据利用递归的思想,将问题简化为判断与当前节点相连的其他节点是否存在终点b
所以可根据以下方法求解。

    def calculate_short_jump(self, a):
        """
        计算无向有环图中两个节点间的最短跳数
        :param a:
        :return:
        """
        self.min_nodes = []
        self.graph1 = self.get_state(self.cur_state)
        # print(self.graph1)
        actions = self.get_next([a[0]], a[0])
        self.fun(actions, [a[0]], a[1])
        res = self.min_nodes[0]
        for x in self.min_nodes:
            if len(res) > len(x):
                res = x
        return res

    def get_next(self, cur, s):
        res = []
        for i, x in enumerate(self.graph1[s]):
            if x == 0 and i not in cur:
                res.append(i)
        return res

    def fun(self, action_space, cur, s):
        if not action_space:
            return False
        for x in action_space:
            if x in cur:
                continue
            if self.graph1[x][s] == 0:
                cur.append(x)
                cur.append(s)
                stack = cur[:]
                self.min_nodes.append(stack)
                cur.pop()
                cur.pop()
            else:
                cur.append(x)
                actions = self.get_next(cur, x)
                res = self.fun(actions, cur, s)
                cur.pop()

猜你喜欢

转载自blog.csdn.net/qq_30615903/article/details/81324248