1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| #include <cstdio> #include <cstring> #include <cstdlib> #include <iostream> #include <queue>
using namespace std;
const int N = 100; const int M = 10000;
int n, m; int head[N]; bool vis[N]; queue <int> que;
struct EdgeNode{ int to; int w; int next; };
EdgeNode Edge[M];
void init() { memset(head, -1, sizeof(head)); memset(vis, false, sizeof(vis)); }
void input() { cin >> n >> m; int i, j, w;
for(int k = 1; k <= m; k++){ cin >> i >> j; Edge[k].to = j; Edge[k].next = head[i]; head[i] = k; } }
void BFS() { que.push(1); int i, k; while(!que.empty()) { if (vis[que.front()]) { que.pop(); continue; } vis[que.front()] = true; for(k = head[que.front()]; ~k; k = Edge[k].next) { if(!vis[Edge[k].to]){ que.push(Edge[k].to); } } printf("%d\n", que.front()); que.pop(); } }
int main() { init(); input(); BFS(); return 0; }
输入: 5 4 1 3 1 2 1 5 3 4
输出: 1 5 2 3 4
|