首页 > 代码库 > 经典DFS问题实践
经典DFS问题实践
八皇后问题:
1 //八皇后问题 经典的DFS问题实践 2 #include<iostream> 3 #include<cmath> 4 #include<algorithm> 5 #include<cstdio> 6 using namespace std; 7 int mat[8][8]; 8 int ans=0; 9 bool check(int row,int col)//最终检查满足要求,则return 1 10 { 11 for(int i=0;i<row;i++) 12 { 13 if(mat[i][col]) 14 return false; 15 for(int j=0;j<8;j++) 16 { 17 //不能在同一条对角线上 18 if(mat[i][j]) 19 { 20 if(fabs(i-row)-fabs(j-col)==0) 21 return 0; 22 else 23 continue; 24 25 } 26 } 27 } 28 return 1; 29 } 30 int dfs(int row) 31 { 32 if(row>=8) 33 { 34 ans++; 35 for(int i=0;i<8;i++) 36 { 37 for(int j=0;j<8;j++) 38 cout<<mat[i][j]<<" "; 39 cout<<endl; 40 } 41 cout<<endl; 42 } 43 for(int col=0;col<8;col++) 44 { 45 if(check(row,col)) 46 { 47 mat[row][col]=1; 48 dfs(row+1); 49 mat[row][col]=0; 50 } 51 } 52 return 0; 53 } 54 int main() 55 { 56 memset(mat,0,sizeof(mat)); 57 dfs(0); 58 cout<<"一共有"<<ans<<"种解决方案"<<endl; 59 }
//最终结果显示一共有92种解决方案
经典DFS问题实践
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。