棋盘问题

C++棋盘问题求解
本文介绍了一个使用C++实现的棋盘问题求解算法。通过深度优先搜索(DFS)的方法,在给定大小的棋盘上放置指定数量的棋子,确保同一行或同一列不会有两个棋子相邻。该程序利用递归进行状态搜索,并统计所有可能的解决方案。
 1 #include<iostream>
 2 #include<cstdio>
 3 #define max 10
 4 using namespace std;
 5 char s[max][max];
 6 int n,k,t=0;
 7 bool deal(int r,int c)
 8 {
 9     for(int i=0;i<n;i++)
10     {
11         if(s[i][c]=='o') return false;
12     }
13     for(int i=0;i<n;i++)
14     {
15         if(s[r][i]=='o') return false;
16     }
17     return true;
18 }
19 void dfs(int c,int m)
20 {
21     int x,y;
22     if(m==k)
23     {
24         t++;
25         return ;
26     }
27     if(c==n*n)
28         return;
29     x=c/n;
30     y=c%n;
31     if(s[x][y]=='#'&&deal(x,y))
32     {
33 
34         s[x][y]='o';
35         dfs(c+1,m+1);
36         s[x][y]='#';
37     }
38     dfs(c+1,m);
39     return ;
40 }
41 int main()
42 {
43     while(scanf("%d%d",&n,&k)&&n!=-1&&k!=-1){
44             t=0;
45         for(int i=0;i<n;i++)
46             for(int j=0;j<n;j++)
47                 cin>>s[i][j];
48         dfs(0,0);
49         printf("%d\n",t);
50     }
51     return 0;
52 }
View Code

 

转载于:https://www.cnblogs.com/fanminghui/p/3242188.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值