简介:
深度优先搜索属于图算法的一种,是一个针对图和树的遍历算法,英文缩写为DFS即Depth First Search。深度优先搜索是图论中的经典算法,利用深度优先搜索算法可以产生目标图的相应拓扑排序表,利用拓扑排序表可以方便的解决很多相关的图论问题,如最大路径问题等等。一般用堆数据结构来辅助实现DFS算法。其过程简要来说是对每一个可能的分支路径深入到不能再深入为止,而且每个节点只能访问一次。
算法思想:
如上图所示,给定初始顶点1,随机选取其邻接点2(如果采用邻接矩阵存储,会先选择序号较小的),顶点2作为新起点,随机选取其邻接点3,3再作为新起点,随机选取其邻接点4,然后在选择5。至此,没有可供选择的顶点,则向上回溯,直至回溯到1,发现其还有未被发现的邻接点8,重复上述步骤,直至遍历完整张图。
算法步骤:
- 从图中某个顶点开始出发,访问此顶点
- 访问起始顶点的未被访问过的邻接点,并选取其作为新的起始顶点
- 重复2,直至其所能到达的邻接点都被访问过
- 开始回溯,寻找新的未被访问过的邻接点,直至全图都被访问过
实现步骤:
- 给定初始顶点,选择此点未被访问过的邻接点
- 访问此临接点,并且将其设置为已访问(采用标记数组,设置是否访问过)
- 重复2,直至所有顶点皆被访问过
代码示例:
邻接矩阵:
#include<iostream>
#include<algorithm>
using namespace std;
#define MAX_SIZE 100
int graph[MAX_SIZE][MAX_SIZE];
bool visted[MAX_SIZE];
void dfs(int s, int n){//递归实现
cout << s << " ";
visted[s] = true;
for(int i = 1; i <= n; i++){
if((graph[s][i] != 0) && (!visted[i]))
dfs(i, n);
}
}
int main(){
int n, m, s;
cin >> n >> m >> s;
for(int i = 0; i < MAX_SIZE; i++){//矩阵初始化
for(int j = 0; j < MAX_SIZE; j++)
graph[i][j] = 0;
}
for(int i = 0; i < m; i++){//更新顶点间关系
int x = rand() % n;
int y = rand() % n;
while(x == 0 || y == 0){//为了便于理解,二维矩阵下标0废弃
x = rand() % n;
y = rand() % n;
}
graph[x][y] = 1;
}
dfs(s, n);
return 0;
}
邻接表
#include<iostream>
#include<algorithm>
using namespace std;
#define MAX_SIZE 100
bool visted[MAX_SIZE];
typedef struct Enode{
int index;
Enode *next;
}*Edge;
struct Vnode{
int data;
Enode *next;
};
void init_v_node(Vnode *apex, int n){
for(int i = 0; i <= n; i++){
apex[i].data = 0;
apex[i].next = NULL;
}
}
void create_list(Vnode *apex, int m, int n){
for(int i = 0; i < m; i++){//更新图的连通情况
int x = rand() % n, y = rand() % n;
while(x == 0 || y == 0){
x = rand() % n;
y = rand() % n;
}
apex[x].data = x;
Edge t = new Enode;
t->index = y;
t->next = apex[x].next;
apex[x].next = t;
}
}
void dfs(Vnode *apex, int s){
cout << s << " ";
visted[s] = true;
Edge p = apex[s].next;
while(p != NULL){
int t = p->index;
if(!visted[t])
dfs(apex, t);
p = p->next;
}
}
int main(){
int n, m;
cin >> n >> m;
Vnode apex[n+1];//顺序表存储顶点
init_v_node(apex, n);
create_list(apex, m, n);
dfs(apex, 1);
return 0;
}