二者的时间复杂度和空间复杂度均相同,不同的是,广度优先遍历更像是树的层次遍历,而深度优先遍历更像是树的前序遍历。
下面是实现的代码:
// BFS.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
char c[4] = { 'A', 'B', 'C', 'D' };
class graph {
public:
vector<vector<int>> arr;
vector<bool> check;
graph(){
//默认生成所需要的图供演示用
/*
图的形状大致如下:
A--B--C
\ | /
C
*/
for (int i = 0; i < 4; i++)
{
vector<int> temp(4, 0);
arr.push_back(temp);
}
arr[0][1] = arr[1][0] = arr[0][3] = arr[3][0] = arr[1][2] = arr[2][1] = arr[1][3] = arr[3][1] = arr[2][3] = arr[3][2] = 1;
}
void printGraph()
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
}
int getNeighbor(int index)
{
bool flag = false;
for (int i = 0; i < 4 && !flag; i++)
{
if (!check[i] && arr[index][i])
{
index = i;
check[i] = true;
flag = true;
}
if (!flag&&i == 3)
index = -1;
}
return index;
}
};
void BFS(graph g)
{
//广度优先遍历该图
//遍历结果为A B D C
queue<int> q;
for (int i = 0; i < 4; i++) g.check.push_back(false);
q.push(0);
g.check[0] = true;
while (!q.empty())
{
//遍历每一个和该节点相连的节点,入队
for (int i = 0; i < 4; i++)
{
if (g.arr[q.front()][i] && !g.check[i])
{
q.push(i);
g.check[i] = true;
}
}
cout << c[q.front()] << " ";
q.pop();
}
cout << endl;
}
int help(graph& g, int index)
{
//深度优先搜索的辅助函数
cout << c[index] << " ";
g.check[index] = true;
int w = g.getNeighbor(index);
if (w == -1)
return w;
else
return help(g, w);
}
void DFS(graph g)
{
//深度优先搜索
for (int i = 0; i < 4; i++) g.check.push_back(false);
help(g, 0);
}
int main()
{
graph g;
g.printGraph();
BFS(g);
DFS(g);
}