1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 5 int n,h[1010]; 6 7 struct M 8 { 9 int data; 10 struct M *next; 11 }*head[1010]; 12 13 struct Q 14 { 15 int step; 16 int site; 17 }; 18 19 void init() 20 { 21 int i; 22 for(i = 1;i <= n; i++) 23 { 24 head[i] = (struct M *)malloc(sizeof(struct M)); 25 head[i]->data = -1; 26 head[i]->next = NULL; 27 } 28 } 29 30 void link(int u,int v) 31 { 32 struct M *p1,*p2,*q; 33 q = (struct M * )malloc(sizeof(struct M)); 34 q->next = NULL; 35 q->data = v; 36 for(p1 = head[u],p2 = p1->next;p2 != NULL; p1 = p1->next,p2 = p2->next) 37 { 38 if(p1->data < v && p2->data > v) 39 { 40 q->next = p1->next; 41 p1->next = q; 42 return; 43 } 44 else if(p2->data == v) {free(q);return;} 45 } 46 p1->next = q; 47 } 48 49 int seek(int mb) 50 { 51 int s,e,temp,step; 52 struct M *p; 53 struct Q q[1010]; 54 s = e = 0; 55 q[e].site = mb; 56 q[e++].step = 0; 57 while(s < e) 58 { 59 mb = q[s].site; 60 temp = q[s++].step; 61 for(p = head[mb];p != NULL;p = p->next) 62 { 63 if(!h[p->data]) 64 { 65 if(p->data == 1) return temp; 66 q[e].site = p->data; 67 q[e++].step = temp + 1; 68 h[p->data] = 1; 69 } 70 } 71 } 72 return -1; 73 } 74 75 int main() 76 { 77 int m,i,u,v,step; 78 while(scanf("%d %d",&n,&m) == 2) 79 { 80 if(n == 1) {printf("0\n");continue;} 81 init(); 82 for(i = 0;i < m; i++) 83 { 84 scanf("%d %d",&u,&v); 85 link(u,v); 86 } 87 memset(h,0,sizeof(h)); 88 h[n] = 1; 89 step = seek(n); 90 if(step >= 0) printf("%d\n",step+1); 91 else printf("NO\n"); 92 } 93 return 0; 94 }