#include<bits/stdc++.h>#include<bits/extc++.h>usingnamespacestd;typedefpair<int,int>pii;intmain(){intn,m;scanf("%d%d",&n,&m);intsqr=200;vector<vector<int>>dog(n),havedog(n,vector<int>(sqr,0));intsrc=0,dst=1;for(inti=0;i<m;i++){intx,y;scanf("%d%d",&x,&y);if(i==0)src=x;if(i==1)dst=x;dog[x].push_back(y);// a dog at x can jump y stepif(y<sqr)havedog[x][y]=1;}for(inti=0;i<n;i++){sort(dog[i].begin(),dog[i].end());dog[i].erase(unique(dog[i].begin(),dog[i].end()),dog[i].end());}// dijvector<int>dist(n,2e9);__gnu_pbds::priority_queue<pii,greater<pii>,__gnu_pbds::thin_heap_tag>q;dist[src]=0;q.push(pii(dist[src],src));while(!q.empty()){intu=q.top().second,dis=q.top().first;q.pop();if(dist[u]!=dis)continue;for(intjump:dog[u]){for(intd=1;u+d*jump<n;d++){if(dist[u+d*jump]>dist[u]+d){dist[u+d*jump]=dist[u]+d;q.push(pii(dist[u+d*jump],u+d*jump));}if(jump<sqr&&havedog[u+d*jump][jump])break;}for(intd=1;u-d*jump>=0;d++){if(dist[u-d*jump]>dist[u]+d){dist[u-d*jump]=dist[u]+d;q.push(pii(dist[u-d*jump],u-d*jump));}if(jump<sqr&&havedog[u-d*jump][jump])break;}}}if(dist[dst]==2e9)cout<<-1<<endl;elsecout<<dist[dst]<<endl;}