classShortestpath ():def __init__(self,x): SELF.N=x Self.dis=[[float ('inf') forIinchRange (0,x+1)] forJinchRange (0,x+1)] forIinchRange (0,x+1): Self.dis[i][i]=0defDijkstra (self,s): Lowdis=[float ('inf')]* (self.n+1) Vis=[false]* (self.n+1) Vis[s]=True forIinchRange (0,self.n+1): Lowdis[i]=Self.dis[s][i] forIinchRange (1, SELF.N): Mind=float ('inf') Minn=-1 forJinchRange (0,self.n+1): if notVis[j]:iflowdis[j]<Mind:mind=LOWDIS[J] Minn=JifMind<float ('inf'): Vis[minn]=True forJinchRange (0,self.n+1): if notVis[j]:ifmind+self.dis[minn][j]<Lowdis[j]: lowdis[j]=mind+Self.dis[minn][j]Else:returnLowdisreturnLowdisdefFloyd (self): Lowdis=self.dis[:] forUinchRange (0,self.n+1): forIinchRange (0,self.n+1): forJinchRange (0,self.n+1): Lowdis[i][j]=min (lowdis[i][u]+Lowdis[u][j],lowdis[i][j])returnlowdisn,m=map (Int,input (). Split ()) d=Shortestpath (n) forIinchRange (0,m): U,v,w=map (Int,input (). Split ())ifD.dis[u][v]>W:d.dis[u][v]=Wlowdis=D.floyd ()ifLowdis[1][n]!=float ('inf'): Print(lowdis[1][n])Else: Print("-1")
Python implements the shortest path problem