#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > adj1[12345];
vector<pair<int, int> > adj2[12345];
int vertex, edge;
int n1, n2;
long long distancee[123456];
int parent[123456];
int matrix[999][999];
long long ANS;
priority_queue<pair<long long, int> > pq;
inline void Take_VertexEdgeWeight() {
  scanf("%d %d", &vertex, &edge);
  for (int i = 0; i < edge; i++)
    scanf("%d", &n1), scanf("%d", &n2), matrix[n1][n2] = 1, matrix[n2][n1] = 1;
  for (int i = 1; i <= vertex; i++)
    for (int j = 1; j <= vertex; j++)
      if (matrix[i][j] == 1)
        adj1[i].push_back({j, 1}), adj1[j].push_back({i, 1});
      else
        adj2[i].push_back({j, 1}), adj2[j].push_back({i, 1});
}
inline void Dijkstra(vector<pair<int, int> > adj1[12345]) {
  for (int i = 1; i <= vertex; i++)
    distancee[i] = (long long)LONG_LONG_MAX, parent[i] = -1;
  int source = 1;
  distancee[source] = 0;
  pq.push({-distancee[source], source});
  while (!pq.empty()) {
    int u = pq.top().second;
    pq.pop();
    for (int i = 0; i < adj1[u].size(); i++) {
      int adjacent = adj1[u][i].first;
      int weight = adj1[u][i].second;
      if (distancee[adjacent] > distancee[u] + weight) {
        distancee[adjacent] = distancee[u] + weight;
        parent[adjacent] = u;
        pq.push({-distancee[adjacent], adjacent});
      }
    }
  }
  ANS = max(ANS, distancee[vertex]);
}
int main() {
  ANS = LONG_LONG_MIN;
  Take_VertexEdgeWeight(), Dijkstra(adj1), Dijkstra(adj2);
  (ANS == LONG_LONG_MAX) ? cout << -1 << endl : cout << ANS << endl;
}
