Advertisement
Fasinir

islands

Aug 28th, 2020 (edited)
7,753
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.26 KB | None | 0 0
  1. from zad1testy import runtests
  2. from copy import copy
  3. from math import inf
  4.  
  5.  
  6. def BFS(G, start,finish):
  7.     from queue import Queue
  8.    
  9.     n = len(G)
  10.     visited = [0 for i in range(n)]
  11.     distance=[inf for i in range(n)]
  12.     parent=[-1 for i in range(n)]
  13.    
  14.     distance[start]=0
  15.     #parent[start]=start
  16.    
  17.     q = Queue()
  18.     q.put([start,0,start])
  19.  
  20.     while not q.empty():
  21.         u,weight,comingfrom = q.get()
  22.  
  23.         if weight>0:
  24.             if visited[u]==0:
  25.                 q.put([u,weight-1,comingfrom])
  26.         else:
  27.             visited[u]=1
  28.             parent[u]=comingfrom
  29.             distance[u]=distance[comingfrom]+G[comingfrom][u]
  30.            
  31.             for i in range(n):
  32.                 if G[u][i]!=None and visited[i] == 0:
  33.                     q.put([i,G[u][i],u])
  34.             visited[u] = 2
  35.     #return distance
  36.     return min(distance[finish],distance[n//3+finish],distance[2*(n//3)+finish])
  37.  
  38. def islands(G, A, B):
  39.     # tu prosze wpisac wlasna implementacje
  40.     n=len(G)
  41.     #podział każdego wierzchołka na 3
  42.     #i dodatkowo wierzchołek [3*n] ma krawędzie o wadze 0 do różnych startów
  43.     Graph=[[None for i in range(3*n+1)] for j in range(3*n+1)]
  44.     # 0<= k <=n-1
  45.     #0*n +k - przybyłem na wyspę mostem
  46.     #1*n +k - przybyłem na wyspę promem
  47.     #2*n +k - przybyłem na wyspę samolotem
  48.     for i in range(n):
  49.         for j in range(n):
  50.             x=G[i][j]
  51.            
  52.             if x==1:
  53.                 Graph[n+i][j]=x
  54.                 Graph[2*n+i][j]=x
  55.             elif x==5:
  56.                 Graph[i][n+j]=x
  57.                 Graph[2*n+i][n+j]=x
  58.             elif x==8:
  59.                 Graph[i][2*n+j]=x
  60.                 Graph[n+i][2*n+j]=x
  61.     #ze startu możemy iść gdziekolwiek
  62.     Graph[3*n][A]=0
  63.     Graph[3*n][n+A]=0
  64.     Graph[3*n][2*n+A]=0
  65.     Graph[3*n][3*n]=0 #potrzebne do poprawnego działania
  66.     """
  67.    for i in range(3*n):
  68.        x=G[A][i%n]
  69.        Graph[A][i]=x
  70.        Graph[n+A][i]=x
  71.        Graph[2*n+A][i]=x
  72.    """ #^ stary pomysł  
  73.     res=BFS(Graph, 3*n,B)
  74.     #print(res[0:n])
  75.     #print(res[n:2*n])
  76.     #print(res[2*n:3*n])
  77.     if res<inf:
  78.         return res
  79.     else:
  80.         return None
  81.    
  82.                    
  83.        
  84.  
  85. runtests( islands )
  86.  
  87.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement