深度優先演算法(DFS)
阿新 • • 發佈:2019-02-15
- 前言:英文縮寫為DFS,可笑的是,我最早去HP公司面試做筆試題的時候, 竟然沒看出來是什麼意思,當然即使知道是這個演算法,當時也不太會寫。本科都是學過的,就是後來忘記了。
- 思路說明:理解深度優先演算法的關鍵在於解決“當下該如何做”。至於下一步應該如何做,和當下應該如何做是一樣的,對!就是用遞迴!自己呼叫自己!
- 遞迴函式模型:
void dfs(int step)
{
判斷邊界,如果到了邊界當然直接返回啦
嘗試每一種可能結果for(i=0;i<n;i++)
{
處理當前步
繼續下一步dfs(step + 1)
}
返回
}
4.應用於圖的遍歷:
這裡我們用二位陣列儲存圖,叫做圖的鄰接矩陣儲存法。
#include<stdio.h>
int graph[100][100];
int book[100];
int m,n,sum;
int que[10000],head,tail;
void dfs(int cur)
{
int i;
printf("%d ",cur);
sum++;
if(sum == n)
{
return;
}
for(i=0;i<n;i++)
{
if(graph[cur][i] == 1 && book[i] == 0)
{
book[i] = 1;
dfs(i);
}
}
return;
}
int main()
{
int i,j,m,a,b;
printf("Please input n lines and columns and m links to build a matrix!\n");
scanf("%d %d",&n,&m);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if (i == j)
graph[i][j] = 0;
else
graph[i][j] = 99999999;
for(i=0;i<m;i++)
{
printf("Set linked line between nodes!\n");
scanf("%d %d",&a,&b);
graph[a][b] = graph[b][a] = 1;
}
book[0] = 1;
dfs(0);
//bfs(0);
return 0;
}
執行結果:
Please input n lines and columns and m links to build a matrix!
5 5
Set linked line between nodes!
0 1
Set linked line between nodes!
0 2
Set linked line between nodes!
0 4
Set linked line between nodes!
1 3
Set linked line between nodes!
2 4
0 1 3 2 4
Press any key to continue