zoukankan      html  css  js  c++  java
  • 采用邻接表表示图的深度优先搜索遍历

    //采用邻接表表示图的深度优先搜索遍历
    #include <iostream>
    using namespace std;
    
    #define MVNum 100
    typedef char VerTexType;
    
    typedef char VerTexType;
    
    typedef struct ArcNode {
    	int adjvex;
    	struct ArcNode* nextarc;
    }ArcNode;
    
    typedef struct VNode {
    	VerTexType data;
    	ArcNode* firstarc;
    }VNode, AdjList[MVNum];
    
    typedef struct {
    	AdjList vertices;
    	int vexnum, arcnum;
    }ALGraph;
    
    bool visited[MVNum];
    
    int LocateVex(ALGraph G, VerTexType v) {
    	for (int i = 0;i < G.vexnum;++i)
    		if (G.vertices[i].data == v)
    			return i;
    	return -1;
    }
    
    void CreateUDG(ALGraph& G) {
    	int i, k;
    	cout << "请输入总顶点数,总边数,以空格隔开:";
    	cin >> G.vexnum >> G.arcnum;
    	cout << endl;
    
    	cout << "输入点的名称,如a" << endl;
    
    	for (i = 0;i < G.vexnum;++i) {
    		cout << "请输入第" << (i + 1) << "个点的名称:";
    		cin >> G.vertices[i].data;
    		G.vertices[i].firstarc = NULL;
    	}
    	cout << endl;
    
    	cout << "输入边依附的顶点,如a b" << endl;
    
    	for (k = 0;k < G.arcnum;++k) {
    		VerTexType v1, v2;
    		int i, j;
    		cout << "请输入第" << (k + 1) << "条边依附的顶点:";
    		cin >> v1 >> v2;
    		i = LocateVex(G, v1);
    		j = LocateVex(G, v2);
    
    		ArcNode* p1 = new ArcNode;
    		p1->adjvex = j;
    		p1->nextarc = G.vertices[j].firstarc;
    		G.vertices[j].firstarc = p1;
    
    		ArcNode* p2 = new ArcNode;
    		p1->adjvex = j;
    		p1->nextarc = G.vertices[j].firstarc;
    		G.vertices[j].firstarc = p2;
    	}
    }
    
    void DFS(ALGraph G, int v) {
    	cout << G.vertices[v].data << "   ";
    	visited[v] = true;
    	ArcNode* p = G.vertices[v].firstarc;
    	while (p != NULL) {
    		int w = p->adjvex;
    		if (!visited[w]) DFS(G, w);
    		p = p->nextarc;
    	}
    }
    
    int main() {
    	cout << "采用邻接表表示图的深度优先搜索遍历";
    	ALGraph G;
    	CreateUDG(G);
    	cout << endl;
    	cout << "无向连通图G创建完成!" << endl;
    
    	cout << "请输入其实的点";
    	VerTexType c;
    	cin >> c;
    
    	int i;
    	for (i = 0;i < G.vexnum;++i) {
    		if (c == G.vertices[i].data)
    			break;
    	}
    	cout << endl;
    	while (i >= G.vexnum) {
    		cout << "该点不存在,请重新输入!" << endl;
    		cout << "请输入遍历连通图的起始点:";
    		cin >> c;
    		for (i = 0;i < G.vexnum;++i) {
    			if (c == G.vertices[i].data)
    				break;
    		}
    	}
    	cout << "深度优先搜索遍历图结果:" << endl;
    	DFS(G, i);
    
    	cout << endl;
    	return 0;
    }
    
    
  • 相关阅读:
    十一:jinja2模板传参
    Python基础—流程控制
    Python字符串格式化输出
    Python基本数据类型--列表、元组、字典、集合
    Python基本数据类型之字符串、数字、布尔
    Python用户输入和代码注释
    Python中变量和常量的理解
    Python程序的执行方式
    Python初识
    python初识
  • 原文地址:https://www.cnblogs.com/ygjzs/p/11877601.html
Copyright © 2011-2022 走看看