Greedy alogorithoms---single source shortest path


p=[[1000,10,  1000, 30, 100],
   [1000,1000,50,  1000,1000],
   [1000,1000,1000,1000,10],
   [1000,1000,20,  1000,60],
   [1000,1000,1000,1000,1000]
]

dist=[0,0,0,0,0]
source=[]
def init():
 source.append(0)
 for i in range(1,5):
  dist[i] = p[0][i]

def get_min():
 temp = 1000
 minimum_index=0
 for i in range(0,5):
  if not i in source:
   if dist[i] < temp:
    temp = dist[i]
    minimum_index =i
 source.append(minimum_index)
 return minimum_index

def calc(minuim_index):
 for j in range(0,5):
  if not j in source:
   if p[minuim_index][j] < 1000:
    temp = p[minuim_index][j]+dist[minuim_index]
    if temp < dist[j]:
     dist[j] =temp


def single_source_shortest_path():
 init()
 for i in range(0,5):
  minuim_index = get_min()
  calc(minuim_index)

single_source_shortest_path()
print dist[4]

posted @ 2016-06-07 19:24  zhaodonglin  Views(168)  Comments(0)    收藏  举报