Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- BFS algorithm in C++
- */
- #include<stdio.h>
- #define maxn 101
- int Q[maxn];
- int top ,back;
- int Node, Edge;
- char link[maxn][maxn];
- char Fg[maxn];
- int Path[maxn];
- void Ini() {
- int i, j;
- for(i = 1; i<= Node; i++) {
- for(j = 1; j<= Node; j++) {
- link[i][j] = 0;
- }
- Path[i] = i;
- Fg[i] = 0;
- }
- }
- void Insert(int n) {
- Q[back++] = n;
- back %= maxn;
- }
- int Pop() {
- int n = Q[top++];
- top %= maxn;
- return n;
- }
- int isEmpty() {
- if(top == back) return 0;
- return 1;
- }
- void PrintPath(int n) {
- if(n == Path[n]) {
- printf("%d",n);
- return;
- }
- PrintPath(Path[n]);
- printf(" %d",n);
- }
- int BFS(int s, int ter) {
- int u, v, i;
- Insert(s);
- Fg[s] = 1;
- while(isEmpty() == 1) {
- v = Pop();
- if(v == ter) {
- PrintPath(v);
- return 1;
- }
- for(i = 1; i<= Node; i++) {
- if(link[v][i] == 1 && Fg[i] == 0) {
- Fg[i] = 1;
- Insert(i);
- Path[i] = v;
- }
- }
- }
- return -1;
- }
- void main() {
- int i, u, v;
- scanf("%d%d",&Node,&Edge);
- Ini();
- while(Edge--) {
- scanf("%d%d",&u,&v);
- link[u][v] = link[v][u] = 1;
- }
- scanf("%d%d",&u,&v);
- BFS(u,v);
- printf("\n");
- }
- /*
- 4 5
- 1 2
- 2 3
- 1 3
- 3 4
- 2 4
- 1 4
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement