搜索與圖論(1)
DFS深度優(yōu)先遍歷
回溯、剪枝、對應一條搜索樹
全排列問題
#include <iostream> #include <algorithm> using namespace std ; const int N = 10 ; int n; int path[N] ; // 存方案的 bool st[N] ; //true表示當前數(shù)組已被用過 void dfs(int u) { if( u==n ) { for(int i = 0; i<n ; i++) cout<<path[i]<<' ' ; cout<<endl ; return ; } for(int i=1; i<=n; i++) if( !st[i] ) // 沒用過 { path[u] = i ; st[i] = true ; dfs(u+1) ; st[i] = false ; //恢復現(xiàn)場 } } int main(){ cin>>n; dfs(0) ; return 0 ; }
n-皇后問題


#include <iostream> #include <algorithm> using namespace std ; const int N = 20 ; int n; char g[N][N] ; // 存方案的 bool l[N], zx[N], fx[N] ; //列 正對角線(左上到右下) 反對角線 void dfs(int u) { if( u==n ) { // 擺了n個皇后,滿足題意 for(int i=0; i<n ; i++) puts(g[i]); cout<<endl; return ; } for(int i=0; i<n; i++) // 枚舉第u行 皇后放在哪一列 if( !l[i] && !zx[u+i] && !fx[n-u+i] ) // 沒用過 坐標轉(zhuǎn)化參考 y=x+b 則 b=y-x,不能是負數(shù) 改成 b=y-x+n { g[u][i] = 'Q' ; l[i] = zx[u+i] = fx[n-u+i] = true ; // 都標為用過了 y=-x+b 則 b = x+y dfs(u+1) ; l[i] = zx[u+i] = fx[n-u+i] = false ; //恢復現(xiàn)場 g[u][i] = '.' ; } } int main(){ cin>>n; for(int i=0; i<n; i++) for(int j=0; j<n; j++) g[i][j] = '.' ; dfs(0) ; return 0 ; }
BFS廣度優(yōu)先遍歷


PS: 本文來自博客園,作者:尊滴菜,轉(zhuǎn)載請注明原文鏈接:http://www.rzrgm.cn/zundicai/p/17379380.html

浙公網(wǎng)安備 33010602011771號