标签:typedef style iostream nod back ref haskell 练习 main
2 1 1 2 2 1 2 1
1 1
#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <queue> #include <algorithm> using namespace std; typedef struct node { int point; int step; }; vector <int> p[100010]; bool vis[100010]; void bfs(int n) { queue <node> Q; node t; t.step=0; t.point=n; vis[n]=1; Q.push(t); while(!Q.empty()) { node v=Q.front();Q.pop(); if(v.point==1) { printf("%d\n",v.step); return ; } vector <int>::iterator it=p[v.point].begin(); while(it!=p[v.point].end()) { if(!vis[*it]) { vis[*it]=1; t.point=*it; t.step=v.step+1; Q.push(t); } it++; } } puts("NO"); } int main() { int n,m,u,v; while(~scanf("%d%d",&n,&m)) { memset(vis,0,sizeof(vis)); for(int i=1;i<=n;i++) p[i].clear();//非常重要 while(m--) { scanf("%d%d",&u,&v); if(u!=v) { p[u].push_back(v); p[v].push_back(u); } } bfs(n); } return 0; }
图结构练习——BFS——从起始点到目标点的最短步数(邻接表+BFS)
标签:typedef style iostream nod back ref haskell 练习 main
原文地址:http://www.cnblogs.com/mfmdaoyou/p/6710438.html