八皇后问题
原始解法DFS
#include <iostream>
#include<stdio.h>
using namespace std;
bool vis[9];
int str[101][9];
int path[9];
int coun = 0;
int n,k;
//int path[]; error1
void DFS(int tmp)
{
if (tmp == 9) {//8个行均排满
coun++;
//tmp = 0;
/*for (int j = 1; j <= 8; j++) {
vis[j] = false;//vis恢复
}*/
for (int i = 1; i <= 8; i++) //{ //error 括号位置
str[coun][i] = path[i];
return;
//}
}
for (int i = 1; i <= 8; i++) {//8个列循环扫描
if (!vis[i]) {
bool flag = false;
// for (int j = 1; j <= tmp; j++) { error 3 当前行的列位置不用比较
for (int j = 1; j < tmp; j++){
if (tmp - i == j - path[j] || tmp + i == path[j] + j) {
flag = true;
break;
}
}
if (flag) continue;
vis[i] = true;
path[tmp] = i;//标记位置
DFS(tmp + 1);
vis[i] = false;
}
}
}
void init()
{
coun = 0;
DFS(1);
}
int main()
{
init();
while (scanf("%d", &n) != EOF) {
cout<<coun<<"----------------"<<endl;
for (int i = 1; i <= 8; i++) {
printf("%d", str[n][i]);
}
printf("\n");
}
return 0;
}
棋盘问题(加上地图和初始的放置行数不定http://poj.org/problem?id=1321
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
bool vis[10];
int n,k,count = 0;
int map[10][10];
void DFS(int x,int t)//层数
{
if(t == k)
{
count++;
return;
}
for(int tmp = x;tmp < n;tmp++)
for(int i = 0;i < n;i++)
if(vis[i]&&map[tmp][i])
{
vis[i] = false;
DFS(tmp+1,t+1);
vis[i] = true;
}
}
int main()
{
while(scanf("%d%d",&n,&k) != EOF && n != -1 && k != -1)
{
// printf("%d %d\n",n,k);
count = 0;
memset(vis,true,sizeof(vis));
memset(map,0,sizeof(map));
int i,j;
char c;
for(i = 0;i < n;i++)
for(j = 0;j < n;j++)
{
while(scanf("%c",&c) && c != '.' && c != '#');
if(c == '.')map[i][j] = 0;
else map[i][j] = 1;
}
//打印地图
// for(i = 0;i < n;i++,cout << endl)
// for(j = 0;j < n;j++)
// printf("%d ",map[i][j]);
DFS(0,0);//第i层
printf("%d\n",count);
}
return 0;
}
/*
8 7
# . . . . . . .
. # . . . . . .
. . # . . . . .
. . . # . . . .
. . . . # . . .
. . . . . # . .
. . . . . . # #
. . . . . . # #
16
*/
)
#include <iostream>
#include <cstdio>
using namespace std;
bool vis[9];
int str[101][9];
int path[9];
int count = 0;
int n;
void DFS(int tmp)//tmp目前排了多少皇后,x目前排的列,path具体排法
{
if (tmp == 8) //8个行均排满
{
for (int i = 0; i < 8; i++)
str[count][i] = path[i] + 1;
count++;
return;
}
for (int i = 0; i < 8; i++) //8个列循环扫描
{
if (!vis[i])
{
bool flag = false;
for (int j = 0; j < tmp; j++)
{
if (tmp - i == j - path[j] || tmp + i == path[j] + j)
{
flag = true;
break;
}
}
if(flag) continue;
vis[i] = true;
path[tmp] = i;//标记位置
DFS(tmp + 1);
vis[i] = false;
}
}
}
int main()
{
DFS(0);
return 0;
}

1万+

被折叠的 条评论
为什么被折叠?



