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;
    } 
    

      

  • 相关阅读:
    预处理
    关键字 static extern
    linux /proc/cpuinfo 不同处理器显示信息
    sscanf函数简介
    阿里云API接口调用
    AD常用命令以及概念
    开源工具、平台列表
    ELK安装部署
    MySQL8.0初体验
    MySQL案例09:Last_IO_Error: Got fatal error 1236 from master when reading data from binary log
  • 原文地址:https://www.cnblogs.com/xzxl/p/8646292.html
Copyright © 2011-2022 走看看