Bootstrap

数据结构之DFS(深搜)

采用深度优先搜索的办法遍历上图,节点之间的关系我采用的是二维数组来存储,若相连相应的值为1,不想连相应的值为0。用visit数组存储节点是否被访问过。注明:图的深度优先搜索遍历得到的结果不唯一

#include "iostream"
using namespace std;
void dfs(int i,int a[][9]);
int visit[9] = { 0 };//0表示未被访问过,1表示访问过
char b[9] = { 'v1','v2','v3','v4','v5','v6','v7','v8','v9' };
int main()
{
	int a[9][9] = { {0,1,0,1,0,0,0,0,0},
					{1,0,1,0,1,0,0,0,0},
	{0,1,0,0,0,1,0,0,0},
	{1,0,0,0,1,0,1,0,0},
	{0,1,0,1,0,0,1,0,0},
	{0,0,1,0,0,0,0,0,0},
	{0,0,0,1,1,0,0,1,0},
	{0,0,0,0,0,0,1,0,1},
	{0,0,0,0,1,0,0,1,0}, };
	dfs(0, a);
	system("pause");

	return 0;
}
void dfs(int i,int a[][9])
{
	if (visit[i] == 1)
		return;
	else
	{
		cout << b[i];
		visit[i] = 1;
		for (int m = 0; m < 9; m++)
		{
			if (a[i][m] == 1)
			{
				dfs(m,a);
			}
		}
	}
}

 

具体应用

输入一个m行n列的字符矩阵,只要有两个‘@’相邻就能组成一个联通块,如下面的字符矩阵有2个联通块

 *   *   *   *   @

 *  @ @ *   @

*   @  *  *   @

@ @ @ *  @

@ @  *  *  @

#include "iostream"
using namespace std;
int visit[5][5] = { 0 };//0表示未访问,1表示访问
int dfs(int i,int j,int a[][5],int &num);
int main()
{
	//-1代表*号,9代表@号
	int a[5][5] = { {-1,-1,-1,-1,9},
	                {-1,9,9,-1,9},
	                {-1,9,-1,-1,9},
	                {9,9,9,-1,9},
	                {9,9,-1,-1,9}};
	int num = 0;//用num表示每个连通图的节点个数
	int n = 0;
	for(int i=0;i<5;i++)
		for (int j = 0; j < 5; j++)
		{
			if (visit[i][j] == 0 && a[i][j] == 9)//符号是@,且未被访问
			{
				num=dfs(i, j, a,num);
				cout << num << endl;
				num = 0;
				n++;
			}
		}
	cout <<"共有几个连通图"<< n;
	
	system("pause");

	return 0;
}
int dfs(int i, int j, int a[][5], int &num)
{
	if (visit[i][j] == 1|| a[i][j]==-1||i<0||i>4||j<0||j>4)
		return num;
	else
	{
		visit[i][j] = 1;
		num = num + 1;
			dfs(i + 1, j, a,num);
			dfs(i, j + 1, a,num);
			dfs(i - 1, j, a,num);
			dfs(i, j - 1, a,num);
	}
}

理解DFS对理解递归有很大的帮助.

 

;