八皇后问题 [OpenJ_Bailian-2698]

在国际象棋棋盘上放置八个皇后,要求每两个皇后之间不能直接吃掉对方。

Input

无输入。

Output

按给定顺序和格式输出所有八皇后问题的解(见Sample Output)。

Sample Input

 

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 
No. 3
1 0 0 0 0 0 0 0 
0 0 0 0 0 1 0 0 
0 0 0 0 0 0 0 1 
0 0 1 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 0 1 0 0 0 0 
0 1 0 0 0 0 0 0 
0 0 0 0 1 0 0 0 
No. 4
1 0 0 0 0 0 0 0 
0 0 0 0 1 0 0 0 
0 0 0 0 0 0 0 1 
0 0 0 0 0 1 0 0 
0 0 1 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 1 0 0 0 0 0 0 
0 0 0 1 0 0 0 0 
No. 5
0 0 0 0 0 1 0 0 
1 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 0 0 0 0 1 
0 0 1 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 0 1 0 0 0 0 
No. 6
0 0 0 1 0 0 0 0 
1 0 0 0 0 0 0 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 0 0 0 1 0 
0 0 1 0 0 0 0 0 
0 0 0 0 0 1 0 0 
No. 7
0 0 0 0 1 0 0 0 
1 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 1 
0 0 0 1 0 0 0 0 
0 1 0 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 1 0 0 0 0 0 
0 0 0 0 0 1 0 0 
No. 8
0 0 1 0 0 0 0 0 
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 
No. 9
0 0 0 0 1 0 0 0 
1 0 0 0 0 0 0 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 0 0 1 0 
0 0 1 0 0 0 0 0 
...以下省略

Hint

此题可使用函数递归调用的方法求解。

 

 

这道题在judge上出现了问题。 然后就是dfs回溯问题。。。

#include
#include
#include
using namespace std;
int n=8;
int a[10][10] = { 0 };
int t = 1;
void print()
{
    printf("No. %d\n", t++);
    for (int i = 0; i < 8; i++)
    {
        for (int j = 0; j < 8; j++)
        {
            printf("%d ", a[j][i]);
        }
        printf("\n");
    }
}
bool judge(int x, int y)
{
    for(int i=0; i=0 && a[x-i-1][y-i-1]) || (y+i+1<8 && a[x-i-1][y+i+1]))
            return false;
     }
    return true;
}
/*
void dfs(int num)
{
    if (num >= 8){
        print();
    }
    for (int i = 0; i < 8; i++)
    {
       if (a[num][i]!=1&&judge(num, i))
        {
            a[num][i] = 1;
            dfs(num + 1);
            a[num][i] = 0;
        }

    }

}
*/

int dfs(int num)
{
    if (num >= 8){
        print();
    }
    for (int i = 0; i < 8; i++)
    {
        if (a[num][i]!=1&&judge(num, i))
        {
            a[num][i] = 1;
            if(dfs(num + 1))
                return 1;
            a[num][i] = 0;
        }

    }
return 0;
}
int main()
{
        dfs(0);
    return 0;
}

 

你可能感兴趣的:(DFS)