http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2830
简单bfs
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <stdio.h> 2 #include <string.h> 3 #include <algorithm> 4 #include <queue> 5 using namespace std; 6 const int N=100005; 7 int head[N],vis[N]; 8 int cnt = 0; 9 struct Edge 10 { 11 int u,v; 12 int next; 13 } edge[4*N]; 14 struct node 15 { 16 int x,step; 17 node(int x,int step):x(x),step(step) {} 18 }; 19 void add(int u,int v) 20 { 21 edge[cnt].u = u; 22 edge[cnt].v = v; 23 edge[cnt].next = head[u]; 24 head[u] = cnt++; 25 } 26 int bfs(int n) 27 { 28 memset(vis,0,sizeof(vis)); 29 queue<node>q; 30 node s(n,0); 31 q.push(s); 32 vis[n] = 1; 33 while(!q.empty()) 34 { 35 node u = q.front(); 36 q.pop(); 37 if (u.x==1) 38 return u.step; 39 for (int j = head[u.x]; j!=-1; j=edge[j].next) 40 { 41 int v = edge[j].v; 42 if (!vis[v]) 43 { 44 q.push(node(v,u.step+1)); 45 vis[v] = 1; 46 } 47 } 48 } 49 return -1; 50 } 51 int main() 52 { 53 int n,m; 54 int u,v; 55 while(~scanf("%d%d",&n,&m)) 56 { 57 cnt = 0; 58 memset(vis,0,sizeof(vis)); 59 memset(head,-1,sizeof(head)); 60 for (int i = 0; i < m; i++) 61 { 62 scanf("%d%d",&u,&v); 63 add(u,v); 64 add(v,u); 65 } 66 int ans = bfs(n); 67 if (ans==-1) 68 puts("NO"); 69 else 70 printf("%d ",ans); 71 } 72 return 0; 73 }