4

ダイクストラのアルゴリズムを書こうとしていますが、コードで特定のことを「言う」方法に苦労しています。視覚化するために、配列を使用して表現したい列を次に示します。

   max_nodes  
   A  B  C         Length       Predecessor       Visited/Unvisited
A 0  1   2             -1                                              U
B 1  0   1             -1                                              U
C 2  1   0             -1                                              U

したがって、以下のコードに見られるように、いくつかの配列があります。

def dijkstra (graph, start, end)

network[max_nodes][max_nodes]
state  [max_nodes][length]
state2 [max_nodes][predecessor]
state3 [max_nodes][visited]
initialNode = 0

    for nodes in graph:
      D[max_nodes][length] = -1
      P[max_nodes][predecessor] = ""
      V[max_nodes][visited] = false

      for l in graph:

       length = lengthFromSource[node] + graph[node][l]
          if length < lengthFromSourceNode[w]:
             state[l][length] = x
             state2[l][predecessor] 
             state3[l][visited] = true
          x +=1

太字の部分は、私が立ち往生している場所です-アルゴリズムのこのセクションを実装しようとしています:

3. 現在のノードについて、未訪問のすべての隣接ノードを考慮し、それらの暫定的な距離を計算します。たとえば、現在のノード (A) の距離が 6 で、別のノード (B) と接続するエッジが 2 の場合、A を介して B までの距離は 6+2=8 になります。この距離が以前に記録された距離よりも小さい場合、距離
4 を上書きします。訪問したノードは二度とチェックされません。現在記録されているその距離は最終的で最小限です

私は正しい軌道に乗っていると思います。「ノードから開始し、ソースからノードまでの長さを取得し、長さが小さい場合は前の値を上書きしてから、次のノードに移動する」という言い方に固執しています

4

2 に答える 2

10

また、辞書を使用してネットワークを保存しました。データの形式は次のとおりです。

source: {destination: cost}

ネットワーク ディクショナリを作成する (ユーザー提供)

net = {'0':{'1':100, '2':300},
       '1':{'3':500, '4':500, '5':100},
       '2':{'4':100, '5':100},
       '3':{'5':20},
       '4':{'5':20},
       '5':{}
       }

最短経路アルゴリズム (ユーザーは開始ノードと終了ノードを指定する必要があります)

def dijkstra(net, s, t):
    # sanity check
    if s == t:
        return "The start and terminal nodes are the same. Minimum distance is 0."
    if s not in net:    # python2: if net.has_key(s)==False:
        return "There is no start node called " + str(s) + "."
    if t not in net:    # python2: if net.has_key(t)==False:
        return "There is no terminal node called " + str(t) + "."
    # create a labels dictionary
    labels={}
    # record whether a label was updated
    order={}
    # populate an initial labels dictionary
    for i in net.keys():
        if i == s: labels[i] = 0 # shortest distance form s to s is 0
        else: labels[i] = float("inf") # initial labels are infinity
    from copy import copy
    drop1 = copy(labels) # used for looping
    ## begin algorithm
    while len(drop1) > 0:
        # find the key with the lowest label
        minNode = min(drop1, key = drop1.get) #minNode is the node with the smallest label
        # update labels for nodes that are connected to minNode
        for i in net[minNode]:
            if labels[i] > (labels[minNode] + net[minNode][i]):
                labels[i] = labels[minNode] + net[minNode][i]
                drop1[i] = labels[minNode] + net[minNode][i]
                order[i] = minNode
        del drop1[minNode] # once a node has been visited, it's excluded from drop1
    ## end algorithm
    # print shortest path
    temp = copy(t)
    rpath = []
    path = []
    while 1:
        rpath.append(temp)
        if temp in order: temp = order[temp]    #if order.has_key(temp): temp = order[temp]
        else: return "There is no path from " + str(s) + " to " + str(t) + "."
        if temp == s:
            rpath.append(temp)
            break
    for j in range(len(rpath)-1,-1,-1):
        path.append(rpath[j])
    return "The shortest path from " + s + " to " + t + " is " + str(path) + ". Minimum distance is " + str(labels[t]) + "."

# Given a large random network find the shortest path from '0' to '5'
print dijkstra(net, s='0', t='5')
于 2013-04-20T06:20:57.287 に答える
2

まず、これは宿題の問題だと思います。最善の提案は、わざわざ自分で書くのではなく、Web 上で既存の実装を見つけることです。 たとえば、かなり見栄えの良いものを次に示します。

車輪を再発明する必要があると仮定すると、そこで参照されているコードは辞書を使用してノード データを格納します。したがって、次のようにフィードします。

{ 
  's': {'u' : 10, 'x' : 5}, 
  'u': {'v' : 1, 'x' : 2}, 
  'v': {'y' : 4}, 
  'x': {'u' : 3, 'v' : 9, 'y' : 2}, 
  'y': {'s' : 7, 'v' : 6}
}

これは、グラフ情報を表示するより直感的な方法のようです。訪問したノードと距離も辞書に保存できます。

于 2011-02-14T22:19:55.333 に答える