OJ1700 八皇后问题 基本搜索算法

基本算法之搜索
总时间限制: 
10000ms
 
内存限制: 
65536kB
描述
在国际象棋棋盘上放置八个皇后,要求每两个皇后之间不能直接吃掉对方。
输入
无输入。
输出
按给定顺序和格式输出所有八皇后问题的解(见Sample Output)。
样例输入

样例输出
No. 1
1 0 0 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 0 0 1 0 0 0 
0 0 0 0 0 0 0 1 
0 1 0 0 0 0 0 0 
0 0 0 1 0 0 0 0 
0 0 0 0 0 1 0 0 
0 0 1 0 0 0 0 0 
No. 2
1 0 0 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 0 1 0 0 0 0 
0 0 0 0 0 1 0 0 
0 0 0 0 0 0 0 1 
0 1 0 0 0 0 0 0 
0 0 0 0 1 0 0 0 
0 0 1 0 0 0 0 0 


最新解法:
#include <bits/stdc++.h>

using namespace std;
bool c[8];//记录第i行是否落子 
int ans[8];//记录每列落在第几行 
int num;
bool ok(int u,int i){
    if(c[i])return false;
    for(int j=0;j<u;++j){
        int t=ans[j];
        if(abs(i-t)==abs(u-j)){
            return false;
        }
    } 
    return true;
}
void dfs(int u){
    if(u==8){
        cout<<"No. "<<++num<<endl;
        for(int i=0;i<8;++i){
            for(int j=0;j<8;++j){
                if(ans[j]==i)cout<<1;//如果第j列落子在第i行那输出1 
                else cout<<0;
                if(j!=7)cout<<" ";
            }
            cout<<endl;
        }
    }
    for(int i=0;i<8;++i){//对每一列选行落子 
        if(ok(u,i)){//如果第u列第i行可以落子,那么落子并且向下一列进行搜索 
            ans[u]=i;
            c[i]=true;
            dfs(u+1);
            c[i]=false;
        }
    }
}
int main(){
    dfs(0);//从第一列开始搜索 
    return 0;
}

 

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
using namespace std;
#define up(i,l,r) for(int i=l;i<=r;++i)
const int ma=1000;
int tot=1;
int a[ma],b[ma],w[ma],m[ma];
int print()
{
    cout<<"No. "<<tot++<<endl;
    up(j,1,8){
        up(i,1,8){
            if(j==a[i])cout<<"1 ";
            else cout<<"0 ";
        }
        cout<<endl;
    }
    
}
int search(int j)
{
    for(int i=1;i<=8;++i){
        if(b[i]==0&&m[i+j]==0&&w[i-j+7]==0){
            a[j]=i;b[i]=1;
            w[i-j+7]=1;m[i+j]=1;
            if(j==8)print();
            else
            search(j+1);
            b[i]=0;
            w[i-j+7]=0;m[i+j]=0;
        }
    }
}
int main()
{
    search(1);
    return 0; 
}

 



posted @ 2020-02-17 00:26  林动  阅读(285)  评论(3编辑  收藏  举报