1. 程式人生 > >求無向有環圖的最短路徑python

求無向有環圖的最短路徑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()