广度优先和深度优先搜索算法

Posted 枝枝

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了广度优先和深度优先搜索算法相关的知识,希望对你有一定的参考价值。

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <string>
#include <queue>
#include <stack>
using namespace std;
//邻接矩阵显示图
void show_graph(vector<vector<int>> &graph)
{
	for (int i = 0; i < graph.size(); i++)
	{
		for (int j = 0; j < graph[i].size(); j++)
		{
			cout << graph[i][j] << "    ";
		}
		cout << endl;
	}
}

//邻接矩阵----深度优先遍历----递归
void DFS_digui(vector<vector<int>> &graph,vector<bool> &visited,int v)
{
	cout << v + 1 << "---->";
	visited[v] = true;
	for (int i = 0; i < graph.size(); i++)
	{
		if (graph[v][i] != 0 && visited[i] == false)
			DFS_digui(graph, visited, i);
	}
}

void BFS(vector<vector<int>> &graph, vector<bool> &visited, int v)
{
	queue<int> myqeue;
	myqeue.push(v);
	cout << v + 1 << "---->";
	visited[v] = true;
	while (!myqeue.empty())
	{
		int mark = myqeue.front();
		myqeue.pop();
		for (int i = 0; i < graph[mark].size(); i++)
		{
			if (graph[mark][i] != 0 && visited[i] == false)
			{
				cout << i + 1 << "---->";
				visited[i] = true;
				myqeue.push(i);
			}
		}
	}
}



int main()
{
	int n = 8;
	vector<vector<int>>  graph(n, vector<int> (n));
	vector<bool> visited(graph.size());
	for (int i = 0; i < visited.size(); i++)
	{
		visited[i] = false;
	}
	graph[0] = { 0, 1, 1, 0, 0, 0, 0, 0};
	graph[1] = { 1, 0, 0, 1, 1, 0, 0, 0 };	
	graph[2] = { 1, 0, 0, 0, 0, 1, 1, 0 };
	graph[3] = { 0, 1, 0, 0, 0, 0, 0, 1 };
	graph[4] = { 0, 1, 0, 0, 0, 0, 0, 1 };
	graph[5] = { 0, 0, 1, 0, 0, 0, 1, 0 };
	graph[6] = { 0, 0, 1, 0, 0, 1, 0, 0 };
	graph[7] = { 0, 0, 0, 1, 1, 0, 0, 0 };
	show_graph(graph);
	cout << endl;
	DFS_digui(graph, visited, 0);
	cout << endl;
	for (int i = 0; i < visited.size(); i++)
	{
		visited[i] = false;
	}
	BFS(graph, visited, 0);
	system("pause");
	return 0;
}

  

以上是关于广度优先和深度优先搜索算法的主要内容,如果未能解决你的问题,请参考以下文章

七十九深度和广度优先搜索算法

深度优先搜索和广度优先搜索、A星算法三种算法的区别和联系?

图的广度、深度优先搜索和拓扑排序

数据结构与算法图遍历算法 ( 深度优先搜索 DFS | 深度优先搜索和广度优先搜索 | 深度优先搜索基本思想 | 深度优先搜索算法步骤 | 深度优先搜索理论示例 )

算法题——深度优先搜索与广度优先搜索

Python算法-深度优先搜索&广度优先搜索(DFS&BFS)