zoukankan      html  css  js  c++  java
  • 图的遍历——DFS(邻接矩阵)

    递归 + 标记

    一个连通图只要DFS一次,即可打印所有的点。

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <cstring>
    #include <malloc.h>
    
    using namespace std;
    
    const int VERTEX_NUM = 20;
    const int INFINITY = 0x7fffffff; 		// 最大int型数,表示权的无限值 
    
    bool vis[VERTEX_NUM];
    
    class Graph {
    public:
    	int vexNum;
    	int edgeNum;
    	int vex[VERTEX_NUM];
    	int arc[VERTEX_NUM][VERTEX_NUM]; 
    };
    
    void createGraph(Graph &G)
    {
    	cout << "please input vexNum and edgeNum: ";
    	cin >> G.vexNum >> G.edgeNum;
    	for (int i = 0; i != G.vexNum; ++i) {
    		cout << "please input no" << i+1 << " vertex: ";
    		cin >>  G.vex[i];
    	}
    	for (int i = 0; i != G.vexNum; ++i) {
    		for (int j = 0; j != G.vexNum; ++j) {
    			G.arc[i][j] = INFINITY;
    		}
    	}
    	for (int k = 0; k != G.edgeNum; ++k) {
    		cout << "please input the vertex of edge(vi, vj) and weight: ";
    		int i, j, w;
    		cin >> i >> j >> w;
    		G.arc[i][j] = w;
    		G.arc[j][i] = G.arc[i][j];			// 无向图 
    	}
    }
    
    void DFS(const Graph &G, int k)
    {
    	vis[k] = true;
    	cout << G.vex[k] << " ";			// 打印图的结点 
    	for (int i = 0; i != G.vexNum; ++i) {
    		if (G.arc[k][i] != INFINITY && !vis[i]) 
    			DFS(G, i);
    	}
    }
    
    void DFSTraverse(const Graph &G)
    {
    	memset(vis, false, VERTEX_NUM);
    	// 连通图一次即遍历完成 
    	for (int i = 0; i != G.vexNum; ++i) {
    		if (!vis[i])
    			DFS(G, i);
    	}
    } 
    
    int main()
    {
    	Graph G;
    	createGraph(G);
    	DFSTraverse(G);
    	return 0;
    } 
    

      

  • 相关阅读:
    图灵机器人,web录音实现自动化交互问答
    人工智能初识,百度AI
    flask web 表单验证 WTForms
    websocket的原理
    DBUtils
    【hdu4704】 Sum——费马小定理+快速幂取模
    【hdu3037】Saving Beans——组合数取模
    【SRM15】题解
    【模板】快速幂取模
    【模板】线性筛法求素数
  • 原文地址:https://www.cnblogs.com/xzxl/p/8646292.html
Copyright © 2011-2022 走看看