• 深度优先搜索遍历连通图的递归算法


    //深度优先搜索遍历连通图的递归算法
    #include <iostream>
    using namespace std;
    
    #define MVNun 100
    typedef char VerTexType;
    typedef int ArcType;
    
    typedef struct {
    	VerTexType vexs[MVNun];
    	ArcType arcs[MVNun][MVNun];
    	int vexnum, arcnum;
    }Graph;
    
    bool visited[MVNun];
    int FirstAdjVex(Graph G, int v);
    int NextAdjVex(Graph G, int v, int w);
    
    int LocateVex(Graph G, VerTexType v) {
    	for (int i = 0;i < G.vexnum;++i) {
    		if (G.vexs[i] == v)
    			return i;
    	}
    	return -1;
    }
    
    void CreateUDN(Graph& G) {
    	int i, j, k;
    	cout << "请输入总顶点数,总边数 , 以空格隔开:";
    	cin >> G.vexnum >> G.arcnum;
    	cout << endl;
    	cout << "输入点的名称,如 a:" << endl;
    
    	for (i = 0;i < G.vexnum;++i) {
    		cout << "请输入第" << (i + 1) << "请输入第";
    		cin >> G.vexs[i];
    	}
    	cout << endl;
    
    	for (i = 0;i < G.vexnum;++i)
    		for (j = 0;j < G.vexnum;++j)
    			G.arcs[i][j] = 0;
    	cout << "输入边依附的顶点,如:a b" << endl;
    	for (k = 0;k < G.arcnum;++k) {
    		VerTexType v1, v2;
    		cout << "请输入第" << (k + 1) << "条边依附的顶点:";
    		cin >> v1 >> v2;
    		i = LocateVex(G, v1);
    		j = LocateVex(G, v2);
    		G.arcs[j][i] = G.arcs[i][j] = 1;
    	}
    }
    
    void DFS(Graph G, int v) {
    	cout << G.vexs[v] << "    ";  visited[v] = true;
    	int w;
    	for (w = FirstAdjVex(G, v); w >= 0; w = NextAdjVex(G, v, w))
    		if (!visited[w]) DFS(G, w);
    }
    
    int FirstAdjVex(Graph G, int v) {
    	int i;
    	for (i = 0;i < G.vexnum;++i) {
    		if (G.arcs[v][i] == 1 && visited[i] == false)
    			return i;
    	}
    	return -1;
    }
    
    int NextAdjVex(Graph G, int v, int w) {
    	int i;
    	for (i = w;i < G.vexnum;++i) {
    		if (G.arcs[v][i] == 1 && visited[i] == false)
    			return i;
    	}
    	return -1;
    }
    
    int main() {
    	cout << "深度优先搜索遍历连通图的递归算法";
    	Graph G;
    	CreateUDN(G);
    	cout << endl;
    	cout << "无向连通图G创建完成!" << endl;
    
    	cout << "请输入遍历连通图的起始点:";
    	VerTexType c;
    	cin >> c;
    
    	int i;
    	for (i = 0;i < G.vexnum;++i) {
    		if (c == G.vexs[i])
    			break;
    	}
    	cout << endl;
    	while (i >= G.vexnum) {
    		cout << "该点不存在,请重新输入!" << endl;
    		cout << "请输入遍历连通图的起始点:";
    		cin >> c;
    		for (i = 0;i < G.vexnum;++i) {
    			if (c == G.vexs[i]) {
    				break;
    			}
    		}
    	}
    	cout << "深度优先搜索遍历连通图结果:" << endl;
    	DFS(G, i);
    
    	cout << endl;
    	return 0;
    }
    
  • 相关阅读:
    LOJ 2553 「CTSC2018」暴力写挂——边分治+虚树
    hdu 1028 & hdu 1398 —— 整数划分(生成函数)
    bzoj 4827 [Hnoi2017] 礼物 —— FFT
    bzoj 4503 两个串 —— FFT
    bzoj 3527 [Zjoi2014] 力 —— FFT
    bzoj 3160 万径人踪灭 —— FFT
    bzoj 2194 快速傅立叶之二 —— FFT
    bzoj 2179 FFT快速傅立叶 —— FFT
    洛谷 P3803 多项式乘法(FFT) —— FFT
    CF 1009 F Dominant Indices —— 长链剖分+指针
  • 原文地址:https://www.cnblogs.com/ygjzs/p/11877592.html
Copyright © 2020-2023  润新知