#include <bits/stdc++.h>
using namespace std;
const int N = 500;
const int M = 125000;
const int INF = 0x7fffffff;
bool vis[N];
int x, y;
struct Edge {
  int from, to, dist;
  Edge(int a, int b, int c) : from(a), to(b), dist(c){};
};
struct Npoint {
  int d, u;
  bool operator<(const Npoint &Np) const { return d > Np.d; }
};
struct Dijkstra {
  int d[N];
  int p[N];
  int n, m;
  vector<Edge> edges;
  vector<int> G[N];
  void cleaner() {
    for (int i = 1; i <= n; i++) G[i].clear();
    edges.clear();
  }
  void AddEdge(int from, int to, int dist) {
    edges.push_back(Edge(from, to, dist));
    m = edges.size();
    G[from].push_back(m - 1);
  }
  void DelEdge(int from, int to) {
    vector<Edge>::iterator iter = edges.begin();
    for (int i = 0; i < G[from].size(); i++) {
      int c = G[from][i];
      if (edges[c].to == to) {
        edges[c].dist = -1;
        edges[c ^ 1].dist = -1;
      }
    }
  }
  void dijkstra(int a) {
    n = x;
    priority_queue<Npoint> Q;
    for (int i = 1; i <= n; i++) d[i] = INF;
    d[a] = 0;
    memset(vis, 0, sizeof(vis));
    Q.push((Npoint){0, a});
    while (!Q.empty()) {
      Npoint x = Q.top();
      Q.pop();
      int u = x.u;
      vis[u] = 1;
      if (d[u] != x.d) continue;
      for (int i = 0; i < G[u].size(); i++) {
        Edge e = edges[G[u][i]];
        if (e.dist == -1) continue;
        if (d[e.to] > d[u] + e.dist) {
          d[e.to] = d[u] + e.dist;
          p[e.to] = G[u][i];
          Q.push(Npoint{d[e.to], e.to});
        }
      }
    }
  }
} dj;
int main() {
  cin >> x >> y;
  int from[M], to[M];
  int flag = 0;
  dj.cleaner();
  for (int i = 0; i < y; i++) {
    cin >> from[i] >> to[i];
    if ((from[i] == 1 && to[i] == x) || (from[i] == x && to[i] == 1)) flag = 1;
  }
  if (flag == 0) {
    for (int i = 0; i < y; i++) {
      dj.AddEdge(from[i], to[i], 1);
      dj.AddEdge(to[i], from[i], 1);
    }
  } else if (flag == 1) {
    for (int i = 1; i < x; i++) {
      for (int j = i + 1; j <= x; j++) {
        dj.AddEdge(i, j, 1);
        dj.AddEdge(j, i, 1);
      }
    }
    for (int i = 0; i < y; i++) {
      dj.DelEdge(from[i], to[i]);
    }
  }
  dj.dijkstra(1);
  if (vis[x] == 0)
    cout << -1 << endl;
  else
    cout << dj.d[x] << endl;
}
