首页 > 代码库 > Graph-DFS-图的深度优先遍历

Graph-DFS-图的深度优先遍历

#include <iostream>

using namespace std;

/*
5 5
1 2
1 3
1 5
2 4
3 5
1 2 4 3 5
--------------------------------
Process exited with return value 0
Press any key to continue . . .
*/

int sum = 0;
int vertx, edge;//点、边的个数 
int Graph[20][20] = {0}, visit[20] = {0};

void DFS(int _n)
{
	if(sum == vertx) return;
	
	sum++;
	
	cout << _n << " ";
	
	for(int i = 1; i <= vertx; i++)
	{
		if(Graph[_n][i] == 1 && visit[i] == 0)
		{
			visit[i] = 1;
			DFS(i);
		}
	}
	
	return;
}

int main()
{
	//点与边的个数,并构造原始数据 
	cin >> vertx >> edge;
	for(int i = 1; i <= vertx; i++)
	{
		for(int j = 1; j <= vertx; j++)
		{
			if(i == j)
			{
				Graph[i][i] = 0;
			}
			Graph[i][j] = 999999;
		}
	}

	//边数据
	for(int i = 1; i <= edge; i++)
	{
		int x, y;
		cin >> x >> y;
		Graph[x][y] = 1;
		Graph[y][x] = 1;
	}
	
	//第一个点设置为已经访问 
	visit[1] = 1;
	
	//开始遍历 
	DFS(1);
	
	return 0;
} 

  

Graph-DFS-图的深度优先遍历