In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.

A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.

You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.

Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.


-----Input-----

The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively.

Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v).

You may assume that there is at most one railway connecting any two towns.


-----Output-----

Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.


-----Examples-----
Input
4 2
1 3
3 4

Output
2

Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4

Output
-1

Input
5 5
4 2
3 5
4 5
5 1
1 2

Output
3



-----Note-----

In the first sample, the train can take the route $1 \rightarrow 3 \rightarrow 4$ and the bus can take the route $1 \rightarrow 2 \rightarrow 4$. Note that they can arrive at town 4 at the same time.

In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.

Difficulty: competition

Starter code:

Solutions:
from collections import deque
n,m=map(int,input().split())
a=[set() for i in range(n+1)]
for i in range(m):
    x,y=map(int,input().split())  
    a[x].add(y)
    a[y].add(x)
if n not in a[1]:
    t=True
else:
    t=False
q=deque()
q.append(1)
z = [-1 for i in range(n+1)]
z[1] = 0
while len(q) > 0:
    v = q.popleft()
    for i in range(1, n+1):
        if t ^ (i in a[v]):
            continue
        if z[i]==-1:
            z[i]=z[v]+1
            q.append(i)
            if i == n:
                print(z[i])
                return
print(-1) 

def read_data():
    n, m = map(int, input().split())
    Es = [[] for i in range(n)]
    for i in range(m):
        u, v = map(int, input().split())
        u -= 1
        v -= 1
        Es[u].append(v)
        Es[v].append(u)
    return n, m, Es

def solve(n, m, Es):
    if n - 1 not in Es[0]:
        return shortestpath(n, Es)
    else:
        Es = trans(n, Es)
        return shortestpath(n, Es)

def trans(n, Es):
    Emat = [[False] * n for i in range(n)]
    for i, row in enumerate(Es):
        for j in row:
            Emat[i][j] = True
    nEs = [[] for i in range(n)]
    for u in range(n):
        for v in range(n):
            if u == v:
                continue
            if Emat[u][v]:
                continue
            nEs[u].append(v)
    return nEs

def shortestpath(n, Es):
    visited = [False] * n
    visited[0] = True
    steps = 0
    fs = [0]
    while fs:
        nfs = []
        for f in fs:
            if f == n - 1:
                return steps
            for v in Es[f]:
                if visited[v]:
                    continue
                nfs.append(v)
                visited[v] = True
        fs = nfs
        steps += 1
    return -1

n, m, Es = read_data()
print(solve(n, m, Es))

from queue import Queue
import sys

def __starting_point():

    def bfs(flag):
        vis = set()
        vis |= {1}
        q = Queue()
        q.put((1, 0))

        while not q.empty():
            u, dis = q.get()
            for v in range(1, n+1):
                if (v not in vis) and (((u, v) in h) == flag):
                    vis |= {v}
                    q.put((v, dis+1))
                    if v == n:
                        return dis+1
        return -1

    n, m = list(map(int, input().split()))

    h = set()
    for _ in range(0, m):
        x, y = list(map(int, input().split()))
        h |= {(x, y)}
        h |= {(y, x)}
    dist1 = bfs(True)
    dist2 = bfs(False)
    # print(dist1, dist2)
    if dist1 == -1 or dist2 == -1:
        print(-1)
    else:
        print(max(dist1, dist2))

__starting_point()

#http://codeforces.com/contest/601/problem/A
import sys
from collections import deque

n, m = list(map(int, input().split()))
g = set()
for i in range(m):
    x, y = list(map(int, input().split()))
    x -= 1
    y -= 1
    g |= {(x, y), (y, x)}

cut = (0, n-1) in g

q = deque()
q.append(0)

d = [-1] * n
d[0] = 0
while len(q):
    x = q.popleft()
    for y in range(n):
        if cut ^ ((x, y) in g) and (d[y] == -1 or d[y] > d[x] + 1):
            d[y] = d[x] + 1
            q.append(y)

print(d[n-1])


def main():
    n, m = list(map(int, input().split()))
    vrtxs = [[False] * n for _ in range(n)]
    for _ in range(m):
        u, v = list(map(int, input().split()))
        u -= 1
        v -= 1
        vrtxs[u][v] = vrtxs[v][u] = True
    if vrtxs[0][n - 1]:
        for u, l in enumerate(vrtxs):
            for v, f in enumerate(l):
                l[v] = not f
            l[u] = False
    avail, nxt, t = [True] * n, [n - 1], 0
    while nxt:
        cur, nxt = nxt, []
        t += 1
        for u in cur:
            for v, f, a in zip(list(range(n)), vrtxs[u], avail):
                if f and a:
                    if not v:
                        print(t)
                        return
                    avail[v] = False
                    nxt.append(v)
    print(-1)


def __starting_point():
    main()

__starting_point()

def main():
    n, m = list(map(int, input().split()))
    vrtxs = [[] for _ in range(n)]
    for _ in range(m):
        u, v = list(map(int, input().split()))
        u -= 1
        v -= 1
        vrtxs[u].append(v)
        vrtxs[v].append(u)
    if n - 1 in vrtxs[0]:
        for u, l in enumerate(vrtxs):
            tmp = [True] * n
            for v in l:
                tmp[v] = False
            tmp[u] = False
            vrtxs[u] = [v for v, f in enumerate(tmp) if f]
    avail, nxt, t = [True] * n, [n - 1], 0
    while nxt:
        cur, nxt = nxt, []
        t += 1
        for u in cur:
            for v in vrtxs[u]:
                if avail[v]:
                    if not v:
                        print(t)
                        return
                    avail[v] = False
                    nxt.append(v)
    print(-1)


def __starting_point():
    main()

__starting_point()

def main():
    n, m = list(map(int, input().split()))
    vrtxs = [[] for _ in range(n)]
    for _ in range(m):
        u, v = list(map(int, input().split()))
        u -= 1
        v -= 1
        vrtxs[u].append(v)
        vrtxs[v].append(u)
    if n - 1 in vrtxs[0]:
        for u, l in enumerate(vrtxs):
            tmp = set(l)
            tmp.add(u)
            vrtxs[u] = [v for v in range(n) if v not in tmp]
    avail, nxt, t = [True] * n, [n - 1], 0
    while nxt:
        cur, nxt = nxt, []
        t += 1
        for u in cur:
            for v in vrtxs[u]:
                if avail[v]:
                    if not v:
                        print(t)
                        return
                    avail[v] = False
                    nxt.append(v)
    print(-1)


def __starting_point():
    main()

__starting_point()

n, m = list(map(int, input().split()))
dp = [[0 for i in range(n + 1)] for j in range(n + 1)]
level = [-1 for i in range(n + 1)]
stack = []

def bfs(src, lvl, flag):
	level[src] = lvl
	stack.append(src)
	p = 0
	while True:
		for i in range(1, n + 1):
			if dp[src][i] == flag:
				#print (i, i)
				if level[i] == -1:
				#	print (i, i)
					stack.append(i)
					level[i] = level[src] + 1
		if len(stack) <= p + 1:
			break
		p += 1
		#print (stack)
		src = stack[p]
		if src == n:
			return level[src]
			break
	return -1

for i in range(m):
	a, b = list(map(int, input().split()))
	dp[a][b] = 1
	dp[b][a] = 1
	
if dp[1][n]:
	print(bfs(1, 0, 0))
	
else:
	print(bfs(1, 0, 1))


from collections import defaultdict as dfdict

def bfs(G,rail_connected=False) :
    level=[1]
    visited=set([1])
    cnt=0
    while len(level)>0 :
        nxtlevel=[]
        for i in level :
            nxt=G[i] if not rail_connected else all_vertice-G[i]
            for j in nxt :
                if j not in visited :
                    if j==n :
                        cnt+=1
                        return cnt
                    else :
                        nxtlevel.append(j)
                        visited.add(j)
        level=nxtlevel
        cnt+=1
    return -1       

n,m=[int(i) for i in input().split()]
rails=dfdict(set)
all_vertice=set([i+1 for i in range(n)])
for _ in range(m) :
    xt,yt=[int(i) for i in input().split()]
    rails[xt].add(yt)
    rails[yt].add(xt)

R=False
if n in rails[1] :
    R=True
else :
    R=False

print(bfs(rails,R))

n, m = list(map(int, input().split()))
a = [[] for i in range(n)]
r = False
for i in range(m):
	x, y = list(map(int, input().split()))
	if (x, y) == (1, n) or (x, y) == (n, 1):
		r = True
	a[x-1].append(y-1)
	a[y-1].append(x-1)
if r:
	for i in range(n):
		s = set(a[i])
		a[i] = [j for j in range(n) if i != j and not j in s]
q = [(0, 0)]
v = set([0])
l = 0
while l < len(q):
	x, d = q[l]
	l += 1
	for y in a[x]:
		if not y in v:
			if y == n-1:
				print(d+1)
				quit()
			q.append((y, d+1))
			v.add(y)
print(-1)


from collections import deque
n, m = tuple(map(int,input().split()))
li,s = deque([0]),set()

for i in range(m):
    a,b = map(int, input().split())
    a -= 1;b-=1
    s.add((a,b))
    s.add((b,a))
reach = (0, n-1) in s
d = [0]
d.extend([-1 for _ in range(n-1)])
while li:
    a =li.popleft()
    for b in range(n):
        if (not(reach and ((a, b) in s)))\
                and(reach or ((a, b) in s))\
                and (d[b] == -1 or d[b] > d[a] + 1):
            d[b] = d[a] + 1
            li.append(b)
print(d[n-1])

from collections import deque
[n,m]=[int(i) for i in input().split()]
routes=[set() for i in range(n+1)]
for i in range(m):
    [x,y]=[int(j) for j in input().split()]
    routes[x].add(y)
    routes[y].add(x)
if n not in routes[1]:
    a=True
else:
    a=False
way=deque()
way.append(1)
b=[-1 for i in range(n+1)]
b[1]=0
while len(way)>0:
    c=way.popleft()
    for i in range(1,n+1):
        if a^(i in routes[c]):
            continue
        if b[i]==-1:
            b[i]=b[c]+1
            way.append(i)
            if i==n:
                print(b[i])
                return
print(-1)

n, m = list(map(int, input().split()))
a = [[] for i in range(n)]
r = False
for i in range(m):
	x, y = list(map(int, input().split()))
	if (x, y) == (1, n) or (x, y) == (n, 1):
		r = True
	a[x-1].append(y-1)
	a[y-1].append(x-1)
if r:
	for i in range(n):
		s = set(a[i])
		a[i] = [j for j in range(n) if i != j and not j in s]
q = [(0, 0)]
v = set([0])
l = 0
while l < len(q):
	x, d = q[l]
	l += 1
	for y in a[x]:
		if not y in v:
			if y == n-1:
				print(d+1)
				quit()
			q.append((y, d+1))
			v.add(y)
print(-1)


n,m=list(map(int,input().split()))
f=[set() for i in range(n)]
g,h=[0]+(n-1)*[10000],[0]+(n-1)*[10000]
for i in range(m):
    u,v=list(map(int,input().split()))
    f[u-1].add(v-1)
    f[v-1].add(u-1)
p={i for i in range(1,n)}
def findrailway(t):
    if t==0:
        for c in f[t]:
            g[c]=g[t]+1
        for c in f[t]:
            findrailway(c)
    if t!=n-1:
        pp=set()
        for c in(f[t]-f[0]):
            if g[c]!=min(g[c],g[t]+1):
                g[c]=g[t]+1
                pp.add(c)
        for c in pp:
            findrailway(c)
def findbusway(t):
    if t==0:
        for c in p-f[t]:
            h[c]=h[t]+1
        for c in p-f[t]:
            findbusway(c)
    if t!=n-1:
        pp=set()
        for c in((p-f[t])-(p-f[0])):
            if h[c]!=min(h[c],h[t]+1):
                h[c]=h[t]+1
                pp.add(c)
        for c in pp:
            findbusway(c)
findrailway(0)
findbusway(0)
print(max(h[n-1],g[n-1]) if(h[n-1]!=g[n-1])and(h[n-1]<10000)and(g[n-1]<10000) else -1)



import sys
from collections import deque

n, m = list(map(int, input().split()))
g = set()
for i in range(m):
    x, y = list(map(int, input().split()))
    x -= 1
    y -= 1
    g |= {(x, y), (y, x)}

cut = (0, n-1) in g

q = deque()
q.append(0)

d = [-1] * n
d[0] = 0
while len(q):
    x = q.popleft()
    for y in range(n):
        if cut ^ ((x, y) in g) and (d[y] == -1 or d[y] > d[x] + 1):
            d[y] = d[x] + 1
            q.append(y)

print(d[n-1])


def bfs(g,n):
    q=[1]
    vis=[1 for x in range(n+1)]
    dis=[0 for x in range(n+1)]
    while len(q):
        cur=q[0]
        q.remove(cur)
        for i in g[cur]:
            if vis[i]:
                q.append(i)
                vis[i]=0
                dis[i]=dis[cur]+1
                if i==n:
                    return dis[n]
    return -1
        

[n,m]=[int(x) for x in input().split()]
rag=[[] for x in range(n+1)]
rog=[[] for x in range(n+1)]
for i in range(m):
    [a,b]=[int(x) for x in input().split()]
    rag[a].append(b)
    rag[b].append(a)
for i in range(1,n+1):
    for j in range(i+1,n+1):
        if j not in rag[i]:
            rog[i].append(j)
            rog[j].append(i)
if n in rag[1]:
    print(bfs(rog,n))
else:
    print(bfs(rag,n))


from queue import PriorityQueue
class Graph:
    to=[]
    n=0
    def __init__(self,_n):
        self.to=[[False]*(_n+1)for i in range(_n+1)]
        self.n=_n
    def add_edge(self,s,t):
        self.to[s][t]=True
        self.to[t][s]=True
    def dijkstra(self):
        flag=self.to[1][self.n]==False
        ans=1
        dis=[-1]*(self.n+1)
        q=PriorityQueue()
        q.put((0,1))
        while q.qsize()>0:
            d1,pos=q.get()
            # print(pos,d1
            if dis[pos]!=-1:
                continue
            dis[pos]=d1

            for i in range(1,self.n+1):
                if self.to[pos][i]!=flag:
                    continue
                nx=i
                if nx==pos:
                    continue
                if dis[nx]==-1:
                    q.put((d1+1,nx))
        return dis[self.n]


gph=Graph(0)
N,M=[0]*2

def read_in():
    # file = open("input.txt")
    nonlocal N,M,gph
    N,M=[int(i)  for i in input().split()]

    gph=Graph(N)
    for i in range(M):
        # line=file.readline()
        s,t=[int(i)  for i in input().split()]

        gph.add_edge(s,t)
        # print(s,t,l)

read_in()

print(gph.dijkstra())

import queue

connect = [[0 for i in range(401)] for j in range(401)]


def bfs(val):
    q = queue.Queue()
    dis = [-1 for i in range(401)]
    dis[1] = 0
    q.put(1)
    while(not q.empty()):
        x = q.get()

        for i in range(1, n+1):
            if connect[x][i] == val and dis[i] == -1:
                dis[i] = dis[x]+1
                q.put(i)
    return dis[n]

temp = input().split()
n = int(temp[0])
m = int(temp[1])

dis = [[[0 for i in range(401)] for j in range(401)] for k in range(2)]

for i in range(m):
    temp = input().split()
    u = int(temp[0])
    v = int(temp[1])
    connect[u][v] = connect[v][u] = 1

print(bfs(1-connect[1][n]))


def bfs_shortest_path(graph, start, goal):
    explored = []
    queue = [[start]]
    while queue:
        path = queue.pop(0)
        node = path[-1]
        if node not in explored:
            neighbours = graph[node]
            for neighbour in neighbours:
                new_path = list(path)
                new_path.append(neighbour)
                queue.append(new_path)
                if neighbour == goal:
                    return len(new_path)-1
            explored.append(node)
    return -1


town_rail = input().split(" ")
town = int(town_rail[0])
rail = int(town_rail[1])
railways = []
graph = {}
for j in range(1,town+1):
    graph[j] = []

for i in range(rail):
    railways.append(input().split(" "))

if ["1", str(town)] in railways or [str(town),"1"] in railways:
    for key in graph:
        for k in range(1,town+1):
            if k != key:
                graph[key].append(k)
    for pair in railways:
        graph[int(pair[0])].remove(int(pair[1]))
        graph[int(pair[1])].remove(int(pair[0]))
else:
    for pair in railways:
        graph[int(pair[0])].append(int(pair[1]))
        graph[int(pair[1])].append(int(pair[0]))
print(bfs_shortest_path(graph, 1, town))

f = lambda: list(map(int, input().split()))
n, m = f()
k = n + 1
s = [[0] * k for i in range(k)]
for j in range(m):
    u, v = f()
    s[u][v] = s[v][u] = 1
d = [-1] * k
d[1] = 0
q = [1]
while q:
    u = q.pop(0)
    for v in range(1, k):
        if s[u][v] != s[1][n] and d[v] == -1:
            d[v] = d[u] + 1
            q.append(v)
print(d[n])


# -*- coding: utf-8 -*-
"""
Created on Tue Nov 28 20:27:33 2017

@author: alter027
"""
import sys

d=[[0 for col in range(500)] for row in range(500)]
v=[0]*500
n, m=list(map(int, input().split()))
for i in range(m):
    x, y=list(map(int, input().split()))
    x -= 1
    y -= 1
    d[x][y] = d[y][x]=1
q = [0]
l = 0

while l < len(q):
    for i in range(1,n):
        if d[0][n-1] != d[q[l]][i] and v[i] == 0 :
            v[i] = v[q[l]] + 1
            q.append(i)
    l += 1

if v[n-1] == 0:
    print(-1)
else:
    print(v[n-1])


from math import inf
from collections import Counter as cntr
n, m = map(int, input().split(' '))
road = [[1 for i in range(n)]for i in range(n)]
railway = [[0 for i in range(n)]for i in range(n)]
for i in range(m):
	u, v = map(int, input().split(' '))
	u -= 1
	v -= 1
	road[u][v] = 0
	road[v][u] = 0
	railway[u][v] = 1
	railway[v][u] = 1

def bfs(graph, source, n):
	visited = [False for i in range(n)]
	d = [inf for i in range(n)]
	q = [source]
	visited[source] = True
	d[source] = 0
	while(q):
		idx = q.pop(0)

		for i in range(n):
			if graph[idx][i] == 1 and visited[i] == False:
				visited[i] = True
				d[i] = d[idx] + 1
				q.append(i)
	return d
l1 = bfs(road, 0, n)
l2 = bfs(railway, 0, n)
ans = max(l1[-1],l2[-1])
print(-1) if ans == inf else print(ans)


f = lambda: list(map(int, input().split()))
n, m = f()
k = n + 1
s = [[0] * k for i in range(k)]
for j in range(m):
    u, v = f()
    s[u][v] = s[v][u] = 1
d = [-1] * k
d[1] = 0
q = [1]
while q:
    u = q.pop(0)
    for v in range(1, k):
        if s[u][v] != s[1][n] and d[v] == -1:
            d[v] = d[u] + 1
            q.append(v)
print(d[n])



f = lambda: list(map(int, input().split()))
n, m = f()
k = n + 1
s = [[0] * k for i in range(k)]
for j in range(m):
    u, v = f()
    s[u][v] = s[v][u] = 1
d = [-1] * k
d[1] = 0
q = [1]
while q:
    u = q.pop(0)
    for v in range(1, k):
        if s[u][v] != s[1][n] and d[v] == -1:
            d[v] = d[u] + 1
            q.append(v)
print(d[n])