06-图1 列出连通集 (25分)

BFS中非STL实现

#include

#define N 15

int G[N][N],Nv,Ne;
bool Visited[N];

void InitVisit()
{
    for(int i=0;ifalse;
}

void DFS(int V)
{
    Visited[V] = true;
    printf("%d ",V);
    for(int i=0;iif(!Visited[i]&&G[V][i])
            DFS(i);
    }
}

void ListComponentsWithDFS()
{
    for(int i=0;iif(!Visited[i])
        {
            printf("{ ");
            DFS(i);
            printf("}\n");
        }
    }
}

void BFS(int V)
{
    const int MAX_SIZE = 100;
    int Queue[MAX_SIZE];
    int first = -1,last = -1;

    Queue[++last] = V;
    Visited[V] = true;
    while(firstint F = Queue[++first];
        printf("%d ",F);
        for(int i=0;iif(G[F][i]&&!Visited[i])
            {
                Queue[++last] = i;
                Visited[i] = true;
            }
        }
    }
}

void ListComponentsWithBFS()
{
    for(int i=0;iif(!Visited[i])
        {
            printf("{ ");
            BFS(i);
            printf("}\n");
        }
    }
}

void CreateGraph()
{
    int v1,v2;

    scanf("%d %d",&Nv,&Ne);
    for(int i=0;ifor(int j=0;j0;
        }
    }
    for(int i=0;iscanf("%d %d",&v1,&v2);
        G[v1][v2] = G[v2][v1] = 1;
    }
}

int main()
{
    CreateGraph();
    InitVisit();
    ListComponentsWithDFS();
    InitVisit();
    ListComponentsWithBFS();
}









对于BFS用STL实现

#include
#include

using namespace std;

#define N 15

int G[N][N],Nv,Ne;
bool Visited[N];

void InitVisit()
{
    for(int i=0;ifalse;
}

void DFS(int V)
{
    Visited[V] = true;
    printf("%d ",V);
    for(int i=0;iif(!Visited[i]&&G[V][i])
            DFS(i);
    }
}

void ListComponentsWithDFS()
{
    for(int i=0;iif(!Visited[i])
        {
            printf("{ ");
            DFS(i);
            printf("}\n");
        }
    }
}

void BFS(int V)
{
    queue<int> Q;
    Q.push(V);
    Visited[V] = true;
    while(!Q.empty()){
        int h = Q.front();
        printf("%d ",h);
        Q.pop();
        for(int i=0;iif(!Visited[i]&&G[h][i]){
                Q.push(i);
                Visited[i] = true;
            }
        }
    }
}

void ListComponentsWithBFS()
{
    for(int i=0;iif(!Visited[i])
        {
            printf("{ ");
            BFS(i);
            printf("}\n");
        }
    }
}

void CreateGraph()
{
    int v1,v2;

    scanf("%d %d",&Nv,&Ne);
    for(int i=0;ifor(int j=0;j0;
        }
    }
    for(int i=0;iscanf("%d %d",&v1,&v2);
        G[v1][v2] = G[v2][v1] = 1;
    }
}

int main()
{
    CreateGraph();
    InitVisit();
    ListComponentsWithDFS();
    InitVisit();
    ListComponentsWithBFS();
}









你可能感兴趣的:(PAT(A))