DFS&BFS(链式前向星实现)

#include <iostream>
#include <cstdio>
#include <cstring>
#define maxn 10000
#define maxm 100
using namespace std;
typedef struct EdgeNode{
    int to;
    int w;
    int next;
};
EdgeNode edges[maxm];
int head[maxm];
int edgenum = 1;
int n, m;
bool s[maxn] = {0};
bool f[maxn] = {0};
void init(){
    memset(head, 0, sizeof(head));
    edgenum = 1;
}
void outputmap(){
    int k;
    for(int i = 1; i <= n; i++){
        if(head[i]!=0) {k = head[i];}
        for( ; k != 0; k = edges[k].next){
            printf("%d->%d %d\n", i, edges[k].to, edges[k].w);
        }
    }
}
void DFS(int x){
    s[x] = true;
    printf("%d\n", x);
    for(int i = head[x]; i != 0; i = edges[i].next){
        if(!s[edges[i].to]){
            DFS(edges[i].to);
        }
    }
}
void BFS(int x){
    int queue[maxn];
    int iq = 0;
    queue[iq++] = x;
    s[x] = true;//标记
    for(int i = 0; i < iq; i++){
        printf("%d\n", queue[i]);
        for(int k = head[queue[i]]; k != 0; k = edges[k].next){
            if(!f[edges[k].to]){
                f[edges[k].to] = true; //标记
                queue[iq++] = edges[k].to;
            }
        }
    }
}
int main()
{
    int a, b, c;
    while(scanf("%d%d", &n, &m)!=EOF){
        init();
        for(int i = 1; i <= m; i++){
            scanf("%d%d%d", &a, &b, &c);
            edges[edgenum].to = b;
            edges[edgenum].w = c;
            edges[edgenum].next = head[a];
            head[a] = edgenum;
            edgenum++;
        }
        outputmap();
        printf("DFS:\n");
        DFS(1);
        printf("BFS:\n");
        BFS(1);
    }
    return 0;
}
8 12
5 8 29
6 1 12
8 3 11
1 2 4
3 1 22
4 3 17
7 4 25
6 5 9
8 7 7
1 6 9
3 2 19
6 7 4

你可能感兴趣的:(c,struct,include)