标签:
2 1 1 2 2 1 2 1
NO 1
#include<iostream> #include<algorithm> #include<stdio.h> #include<string.h> #include<stdlib.h> #include<queue> #include<vector> using namespace std; const int maxn = 1001; struct node { int x; int ans; }; int n,m; vector<int>p[maxn]; int v[maxn]; int flag; void BFS() { memset(v,0,sizeof(v)); queue<struct node>q; while(!q.empty()) { q.pop(); } struct node t,f; t.x = n; t.ans = 0; q.push(t); v[t.x] = 1; while(!q.empty()) { t = q.front(); q.pop(); for(int i=0;i<p[t.x].size();i++) { if(v[p[t.x][i]] == 0) { f.x = p[t.x][i]; f.ans = t.ans + 1; if(p[t.x][i] == 1) { flag = f.ans; return ; } q.push(f); v[p[t.x][i]] = 1; } } } } int main() { while(scanf("%d%d",&n,&m)!=EOF) { flag = 0; for(int i=0;i<=n;i++) { p[i].clear(); } int x,y; for(int i=0;i<m;i++) { scanf("%d%d",&x,&y); p[x].push_back(y); } BFS(); if(flag) { printf("%d\n",flag); } else { printf("NO\n"); } } return 0; }
SDUT 2139 图结构练习——BFS——从起始点到目标点的最短步数(BFS + vector)
标签:
原文地址:http://blog.csdn.net/yeguxin/article/details/45226387