1. 程式人生 > >BFS和DFS演算法原理(通俗易懂版)

BFS和DFS演算法原理(通俗易懂版)

#include<cstdio>#include<cstring> #include<queue> #include<algorithm> using namespace std; const int maxn=100; bool vst[maxn][maxn]; // 訪問標記 int dir[4][2]={0,1,0,-1,1,0,-1,0}; // 方向向量 struct State // BFS 佇列中的狀態資料結構 { int x,y; // 座標位置 int Step_Counter; // 搜尋步數統計器 }; State a[maxn]; bool CheckState(State s) // 約束條件檢驗 { if(!vst[s.x][s.y] && ...) // 滿足條件 return 1; else // 約束條件衝突 return 0; } void bfs(State st) { queue <State> q; // BFS 佇列 State now,next; // 定義2 個狀態,當前和下一個 st.Step_Counter=0; // 計數器清零 q.push(st); // 入隊 vst[st.x][st.y]=1; // 訪問標記 while(!q.empty()) { now=q.front(); // 取隊首元素進行擴充套件 if(now==G) // 出現目標態,此時為Step_Counter 的最小值,可以退出即可 { ...... // 做相關處理 return; } for(int i=0;i<4;i++) { next.x=now.x+dir[i][0]; // 按照規則生成下一個狀態 next.y=now.y+dir[i][1]; next.Step_Counter=now.Step_Counter+1; // 計數器加1 if(CheckState(next)) // 如果狀態滿足約束條件則入隊 { q.push(next); vst[next.x][next.y]=1; //訪問標記 } } q.pop(); // 隊首元素出隊 }  return; } int main() { ......  return 0; } DFS: DFS: /* 該DFS 框架以2D 座標範圍為例,來體現DFS 演算法的實現思想。 */ #include<cstdio> #include<cstring> #include<cstdlib> using namespace std; const int maxn=100; bool vst[maxn][maxn]; // 訪問標記 int map[maxn][maxn]; // 座標範圍 int dir[4][2]={0,1,0,-1,1,0,-1,0}; // 方向向量,(x,y)周圍的四個方向 bool CheckEdge(int x,int y) // 邊界條件和約束條件的判斷 { if(!vst[x][y] && ...) // 滿足條件 return 1; else // 與約束條件衝突 return 0; } void dfs(int x,int y) { vst[x][y]=1; // 標記該節點被訪問過 if(map[x][y]==G) // 出現目標態G { ...... // 做相應處理 return; } for(int i=0;i<4;i++) { if(CheckEdge(x+dir[i][0],y+dir[i][1])) // 按照規則生成下一個節點 dfs(x+dir[i][0],y+dir[i][1]); } return; // 沒有下層搜尋節點,回溯 } int main() { ...... return 0; }