Guest User

Untitled

a guest
Dec 16th, 2021
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. #import sys
  2. from time import perf_counter
  3.  
  4. def minDistance():
  5.     global dist
  6.     global sptSetList
  7.     min = 99999 #sys.maxsize
  8.     for v in sptSetList:
  9.         if dist[v] < min:
  10.             min = dist[v]
  11.             min_index = v
  12.     return min_index
  13.  
  14.  
  15. with open('input15') as f:
  16.     lines = f.read().splitlines()
  17. t1=perf_counter()
  18. maxx=len(lines[0])
  19. maxy=len(lines)
  20. fold=5
  21.  
  22. V = (maxy*fold)*(maxx*fold)
  23. graph = [[] for node in range(V)]
  24. dist = [99999]*V #[sys.maxsize] * V
  25.  
  26. print("Populate graph")
  27. for y in range(maxy*fold):
  28.     for x in range(maxx*fold):
  29.         if x>0:
  30.             risk=(int(lines[y%maxy][(x-1)%maxx])+(x-1)//maxx+y//maxy)
  31.             risk=(risk-1)%9+1
  32.             graph[y*maxx*fold+x].append([y*maxx*fold+(x-1),risk])
  33.         if y>0:
  34.             risk=(int(lines[(y-1)%maxy][x%maxx])+x//maxx+(y-1)//maxy)
  35.             risk=(risk-1)%9+1
  36.             graph[y*maxx*fold+x].append([(y-1)*maxx*fold+x,risk])
  37.         if x<(maxx*fold-1):
  38.             risk=(int(lines[y%maxy][(x+1)%maxx])+(x+1)//maxx+y//maxy)
  39.             risk=(risk-1)%9+1
  40.             graph[y*maxx*fold+x].append([y*maxx*fold+(x+1),risk])
  41.         if y<(maxy*fold-1):
  42.             risk=(int(lines[(y+1)%maxy][x%maxx])+x//maxx+(y+1)//maxy)
  43.             risk=(risk-1)%9+1
  44.             graph[y*maxx*fold+x].append([(y+1)*maxx*fold+x,risk])
  45. print("Compute solution")
  46.  
  47. dist[0] = 0
  48. sptSet = [False] * V
  49. sptSetList=[]
  50. for v in range(V):
  51.     sptSetList.append(v)
  52.  
  53. for cout in range(V):
  54.     if cout%1000==0:
  55.         print(cout//1000,'/',V//1000)
  56.     u = minDistance()
  57.    
  58.     sptSet[u] = True
  59.     sptSetList.remove(u)
  60.  
  61.     for nd in graph[u]:
  62.         if sptSet[nd[0]] == False and dist[nd[0]] > dist[u] + nd[1]:
  63.             dist[nd[0]] = dist[u] + nd[1]
  64.                        
  65. print("Distance of vertex from source")
  66. print(V-1, "t", dist[V-1])
  67. t2=perf_counter()
  68. print("Elapsed time: %.3f ms" % round(1e3*(t2-t1),3))
  69.  
Advertisement
Add Comment
Please, Sign In to add comment