602C - The Two Routes - CodeForces Solution


graphs *1600

Please click on ads to support us..

Python Code:

import collections
n,r=map(int,input().split())
train={i:[] for i in range(1,n+1)}
bus={i:[j for j in range(1,n+1) if j!=i] for i in range(1,n+1)}
for i in range(r):
    a,b=map(int,input().split())
    train[a].append(b)
    train[b].append(a)
    bus[a].remove(b)
    bus[b].remove(a)
def bfs(s,dic):
    q=collections.deque([[s,0]])
    vis=set([s])
    t=-1
    while q:
        a,b=q.popleft()
        if a==n:
            t=b
            break
        for i in dic[a]:
            if i not in vis:
              vis.add(i)
              q.append([i,b+1])
    return t

a=(bfs(1,train))
b=(bfs(1,bus))
if a<0 or b<0:
    print(-1)
else:
    print(max(a,b))


Comments

Submit
0 Comments
More Questions

253A - Boys and Girls
1327E - Count The Blocks
984A - Game
12B - Correct Solution
1355B - Young Explorers
485A - Factory
628A - Tennis Tournament
1436B - Prime Square
1707B - Difference Array
1422C - Bargain
1611F - ATM and Students
660A - Co-prime Array
1692F - 3SUM
1470A - Strange Birthday Party
190D - Non-Secret Cypher
1721B - Deadly Laser
1721C - Min-Max Array Transformation
1721A - Image
1180C - Valeriy and Deque
557A - Ilya and Diplomas
1037D - Valid BFS
1144F - Graph Without Long Directed Paths
1228A - Distinct Digits
355B - Vasya and Public Transport
1230A - Dawid and Bags of Candies
1530A - Binary Decimal
1472D - Even-Odd Game
441C - Valera and Tubes
1328E - Tree Queries
265A - Colorful Stones (Simplified Edition)