N, M = [ int(x) for x in input().split() ]
train = [ [ False for b in range(N) ] for a in range(N) ]
for m in range(M):
a, b = [ int(x)-1 for x in input().split() ]
train[a][b] = train[b][a] = True
if train[0][N-1]: train = [ [ not train[a][b] for b in range(N) ] for a in range(N) ]
dist = [ N+1 for n in range(N) ]
dist[0] = 0
from queue import Queue
Q = Queue()
Q.put(0)
while not Q.empty():
kde = Q.get()
for kam in range(N):
if train[kde][kam]:
if dist[kam] > dist[kde]+1:
dist[kam] = dist[kde]+1
Q.put(kam)
print( -1 if dist[N-1]==N+1 else dist[N-1] )
TiwgTSA9IFsgaW50KHgpIGZvciB4IGluIGlucHV0KCkuc3BsaXQoKSBdCgp0cmFpbiA9IFsgWyBGYWxzZSBmb3IgYiBpbiByYW5nZShOKSBdIGZvciBhIGluIHJhbmdlKE4pIF0KZm9yIG0gaW4gcmFuZ2UoTSk6CiAgICBhLCBiID0gWyBpbnQoeCktMSBmb3IgeCBpbiBpbnB1dCgpLnNwbGl0KCkgXQogICAgdHJhaW5bYV1bYl0gPSB0cmFpbltiXVthXSA9IFRydWUKaWYgdHJhaW5bMF1bTi0xXTogdHJhaW4gPSBbIFsgbm90IHRyYWluW2FdW2JdIGZvciBiIGluIHJhbmdlKE4pIF0gZm9yIGEgaW4gcmFuZ2UoTikgXQoKZGlzdCA9IFsgTisxIGZvciBuIGluIHJhbmdlKE4pIF0KZGlzdFswXSA9IDAKZnJvbSBxdWV1ZSBpbXBvcnQgUXVldWUKUSA9IFF1ZXVlKCkKUS5wdXQoMCkKd2hpbGUgbm90IFEuZW1wdHkoKToKICAgIGtkZSA9IFEuZ2V0KCkKICAgIGZvciBrYW0gaW4gcmFuZ2UoTik6CiAgICAgICAgaWYgdHJhaW5ba2RlXVtrYW1dOgogICAgICAgICAgICBpZiBkaXN0W2thbV0gPiBkaXN0W2tkZV0rMToKICAgICAgICAgICAgICAgIGRpc3Rba2FtXSA9IGRpc3Rba2RlXSsxCiAgICAgICAgICAgICAgICBRLnB1dChrYW0pCgpwcmludCggLTEgaWYgZGlzdFtOLTFdPT1OKzEgZWxzZSBkaXN0W04tMV0gKQ==