求有向圖的最短路徑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()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章