无向图,邻接矩阵结构
- /*
- 图
- 采用邻接矩阵存储
- DFS采用递归方案
- By______H4-breeze[在等带mm来自习的时候]
- Apr.28th.2012
- */
- #include<iostream>
- using namespace std;
- #define VertexNum 10 //定义顶点数量最多10个,#define不带分号
- //图的相关数据结构
- typedef struct{ //图的数据结构:顶点数据+边数据+顶点数+边数
- char vexs[VertexNum]; //顶点表
- int edges[VertexNum][VertexNum];
- int v,e; //顶点数+边数
- }Graph;
- //定义队列数据结构,在BFS时用到
- typedef struct qNode{
- int front;
- int rear;
- int count;
- int p[VertexNum];
- }queue;
- //全局变量,存放访问信息
- int visited[VertexNum];
- void CreatGraph(Graph *G); //创建一个图
- void FS(Graph *G,int choice); //对图G实行深度优先遍历,choice为选择遍历方式
- void dfs(Graph *G,int i); //对图G从顶点i出发实行DFS遍历的具体算法,采用递归方案
- void bfs(Graph *G,int i); //对图G从顶点i出发实行BFS遍历的具体算法,采用队列方案
- //主函数体
- int main(void)
- {
- Graph *graph;
- graph = (Graph *)malloc(sizeof(Graph));
- CreatGraph(graph);
- cout << "----DFS----" << endl;
- FS(graph,0);
- cout << "----BFS----" << endl;
- FS(graph,1);
- return 0;
- }
- //创建图
- void CreatGraph(Graph *G)
- {
- int i,j,k;
- cout << "Input number of vertex and number of edges" << endl;
- cin >> G->v >> G->e;
- cout << "Input data of vertex" << endl;
- for(i = 0;i < G->v; i++)
- {
- cin >> G->vexs[i];
- }
- for(i = 0; i < G->v; i++)
- for(j = 0;j < G->v; j++)
- {
- G->edges[i][j] = 0; //初始化为独立顶点
- }
- cout << "Input information of edges.e.g:input 1 and 2 represents vertex 1 connects with 2" << endl;
- for(k = 0; k < G->v; k++)
- {
- cin >> i >> j;
- G->edges[i-1][j-1]=1; //设定各个顶点间的链接情况:1为相连;0为断开
- }
- }
- //遍历初始化即方案选择
- void FS(Graph *G,int choice) //从图G的顶点i开始DFS
- {
- int i = 0;
- for(i = 0;i < G->v; i++)
- visited[i] = 0; //初始化所有顶点都没有被访问
- switch(choice)
- {
- case 0:
- for(i = 0;i < G->v; i++)
- dfs(G,i); //从第一个顶点开始访问
- break;
- case 1:
- for(i = 0;i < G->v; i++)
- bfs(G,i);
- break;
- }
- }
- //DFS遍历具体实现算法,递归方案
- void dfs(Graph *G,int i)
- {
- if(visited[i] == 0)
- {
- cout << "Vertex " << i+1 << " has been visited!" << endl;
- visited[i] = 1;
- for(int j = 0;j < G->v; j++)
- {
- if(G->edges[i][j] != 0 && visited[j] == 0)
- dfs(G,j); //递归从与顶点i有连接的且尚未被访问的顶点j开始访问
- }
- }
- }
- //BFS遍历具体算法,队列方案
- void bfs(Graph *G,int i)
- {
- int j,k;
- queue *q=(queue *)malloc(sizeof(queue)); //新建一个队列
- q->front = q->rear = q->count = 0; //空队列
- //把当前正在访问的顶点进队,以后会从这个顶点出发遍历他的还没有被访问的邻顶点
- visited[i] = 1;
- cout << "Vertex " << i+1 << " has been visited!" << endl;
- q->p[q->rear] = i; //
- q->rear++;
- q->count++; //进队 rear永远指向对尾,front永远指向对头
- while(q->count > 0) //最好不要用q->count != 0。因为可能为负数,循环有问题
- {
- j = q->p[q->front];
- q->front++;
- q->count--; //出队
- if(visited[j] == 0)
- {
- for(k = 0; k < G->v; k++)
- {
- if(G->edges[j][k] != 0 && visited[k] == 0) //边存在且尚未被访问
- {
- cout << "Vertex " << k+1 << " has been visited!" << endl;
- visited[k] = 1;
- q->p[q->rear] = k;
- q->rear++;
- q->count++; //入队
- }
- }
- }
- }
- }