数据结构——图的邻接表的广度优先搜索

#include 
using namespace std;

#include 
#include 

#define OK 1
#define NULL 0
#define MAX_VERTEX_NUM 20 // 最大顶点数

typedef char VertexType;
typedef int VRType;
typedef int InforType;

typedef struct ArcNode
{
        int adjvex;   //该边所指的顶点的位置
        struct ArcNode *nextarc;   //指向下一条边的指针
        //int weight;  //边的权
}ArcNode;   //表的结点

typedef struct VNode
{
        VertexType data;        //顶点信息(如数据等)
        ArcNode *firstarc;        //指向第一条依附该顶点的边的弧指针
}VNode, AdjList[MAX_VERTEX_NUM];   //头结点

typedef struct ALGraph
{
        AdjList vertices;
        int visited[MAX_VERTEX_NUM];    //访问标志数组
        int vexnum, arcnum;   //图的当前顶点数和弧数
}ALGraph;

//初始化图
void init_ALGraph(ALGraph &g)
{
    for(int i=0;i= G.vexnum)
                return -1;
        return i;
}

//增加节点
void add_vex(ALGraph &G)
{
        cout<<"输入无向图顶点数: "<>G.vexnum;
        //getchar();    //吃回车
        cout<<"输入顶点信息:"<>G.vertices[i].data;   //构造顶点向量
                G.vertices[i].firstarc = NULL;
                //getchar();
        }
}

//增加边
void add_arc(ALGraph &G)
{
        ArcNode *s, *t;

        cout<<"输入无向图边数: "<>G.arcnum;
        char v1, v2;
        cout<<"输入边信息:"<>v1>>v2;
                int i = LocateVex(G, v1);
                int j = LocateVex(G, v2);    //确定v1 , v2在G中的位置

                s = (ArcNode*) malloc (sizeof(ArcNode));
                t = (ArcNode*) malloc (sizeof(ArcNode));

                s->adjvex = j;   //该边所指向的顶点的位置为j
                s->nextarc = G.vertices[i].firstarc;
                G.vertices[i].firstarc =s;

                t->adjvex = i;   //该边所指向的顶点的位置为j
                t->nextarc = G.vertices[j].firstarc;
                G.vertices[j].firstarc =t;
        }
}

//构造邻接链表
void CreateUDN(ALGraph &G)
{
        add_vex(G);        //增加节点
        add_arc(G);        //增加边        
}


void PrintAdjList(ALGraph &G)
{
        int i;
        ArcNode *p;
        cout<<"编号    顶点    邻点编号"<nextarc)
                        cout<adjvex<<"  ";
                cout<nextarc)
                if( !g.visited[p->adjvex] )
                {
                    Visit(g,p->adjvex);
                    Queue[rear++]=p->adjvex;    //入队
                }
        }//while
}

int main()
{
        ALGraph G;    
        init_ALGraph(G);    //初始化图    
        CreateUDN(G);        //创建图
        PrintAdjList(G);    //打印图
        BFSTraverse(G,0);    //广度优先搜索
        return 0;
}

你可能感兴趣的:(数据结构)