深度和广度优先搜索

#include<iostream>
using namespace std;
#define maxvex 100
typedef struct
{
    int a[maxvex][maxvex];
    int vex;
}Graph;
int visiteded[maxvex];
void DFS(Graph G,int v)
{
    printf("v%d ",v+1);
    visiteded[v]=1;
    for(int j=0;j<G.vex;j++)
        if(G.a[v][j]==1&&visiteded[j]==0)
            DFS(G,j);
}
void DFStravse(Graph G)
{
    printf("深度优先遍历结果为: \n");
    for(int i=0;i<G.vex;i++)
        if(!visiteded[i])
            DFS(G,i);
}
int main()
{
    memset(visiteded,0,sizeof(visiteded));
    int i,j;
    Graph G;
    printf("\n输入图中顶点数:");
    scanf("%d",&G.vex);
    printf("\n按行输入图的邻接矩阵:\n");
    for(i=0;i<G.vex;i++)
        for(j=0;j<G.vex;j++)
            scanf("%d",&G.a[i][j]);
        DFStravse(G);
        printf("\n");
    return 0;
}
/*
输入图中顶点数:8

按行输入图的邻接矩阵:
0 1 1 0 0 0 0 0
1 0 0 1 1 0 0 0
1 0 0 0 0 1 1 0
0 1 0 0 0 0 0 0
0 1 0 0 0 0 0 1
0 0 1 0 0 0 0 1
0 0 1 0 0 0 0 0
0 0 0 0 1 1 0 0
深度优先遍历结果为:
v1 v2 v4 v5 v8 v6 v3 v7
Press any key to continue
*/
/*#include<iostream>
#include<queue>
using namespace std;
#define Maxvex 100
typedef struct
{
    int a[Maxvex][Maxvex];
    int n;
}MGraph;
int visited[Maxvex];
void BFSM(MGraph *G,int k)
{
    int j;
    queue <int> Q;
    printf("广度优先遍历结点:结点v%d\n",k+1);
        visited[k]=1;
    Q.push(k);
    while(!Q.empty())
    {
        k=Q.front();
        Q.pop();
        for(j=0;j<G->n;j++)
            if(G->a[k][j]==1&&visited[j]==0)
            {
                printf("广度优先遍历结点:结点v%d\n",j+1);
                    visited[j]=true;
                Q.push(j);
            }
    }
}
void BFSTraveseM(MGraph *G)
{
    int i=0;
    for(i=0;i<G->n;i++)
       if(!visited[i])
            BFSM(G,i);
}
int main()
{
    MGraph *G=new MGraph;
    memset(visited,0,sizeof(visited));
    printf("\n请输入图中顶点个数:\n");
    scanf("%d",&(G->n));
    printf("\n按行输入图的邻接矩阵:\n");
    for(int i=0;i<G->n;i++)
        for(int j=0;j<G->n;j++)
            scanf("%d",&G->a[i][j]);
        BFSTraveseM(G);
    return 0;
}*/
/*

请输入图中顶点个数:
8

按行输入图的邻接矩阵:
0 1 1 0 0 0 0 0
1 0 0 1 1 0 0 0
1 0 0 0 0 1 1 0
0 1 0 0 0 0 0 0
0 1 0 0 0 0 0 1
0 0 1 0 0 0 0 1
0 0 1 0 0 0 0 0
0 0 0 0 1 1 0 0
广度优先遍历结点:结点v1
广度优先遍历结点:结点v2
广度优先遍历结点:结点v3
广度优先遍历结点:结点v4
广度优先遍历结点:结点v5
广度优先遍历结点:结点v6
广度优先遍历结点:结点v7
广度优先遍历结点:结点v8
Press any key to continue*/

 

posted @ 2012-11-03 03:03  myth_HG  阅读(245)  评论(0编辑  收藏  举报