#include <bits/stdc++.h>
using namespace std;
void err(istream_iterator<string> it) {}
template <typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
  cerr << *it << " = " << a << endl;
  err(++it, args...);
}
void faster() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
}
long long n, m;
vector<long long> vst;
vector<long long> dis;
long long bfs(long long u, vector<set<long long> > &adj) {
  queue<pair<long long, long long> > q;
  q.push(make_pair(u, 0));
  while (!q.empty()) {
    long long v, d;
    tie(v, d) = q.front();
    q.pop();
    vst[v] = 1;
    dis[v - 1] = d;
    for (auto e : adj[v]) {
      if (!vst[e]) {
        q.push(make_pair(e, d + 1));
        vst[e] = 1;
      }
    }
  }
  return dis[n - 1];
}
void solve() {
  cin >> n >> m;
  vector<set<long long> > adj(n + 1);
  vst.resize(n + 1);
  dis.resize(n);
  fill((dis).begin(), (dis).end(), 1000);
  bool flag = true;
  for (__typeof(m) i = (0) - ((0) > (m)); i != (m) - ((0) > (m));
       i += 1 - 2 * ((0) > (m))) {
    long long x, y;
    cin >> x >> y;
    if (min(x, y) == 1 && max(x, y) == n) flag = false;
    adj[x].insert(y);
    adj[y].insert(x);
  }
  if (flag) {
    long long dist = bfs(1, adj);
    if (dist == 1000) dist = -1;
    cout << dist << endl;
  } else {
    vector<set<long long> > adjp(n + 1);
    for (long long i = 1; i < n + 1; i++) {
      for (long long j = 1; j < n + 1; j++) {
        if (j != i && !adj[i].count(j)) adjp[i].insert(j);
      }
    }
    long long dist = bfs(1, adjp);
    if (dist == 1000) dist = -1;
    cout << dist << endl;
  }
}
signed main() {
  faster();
  long long t = 1;
  while (t--) solve();
}
