OpenJ_Bailian - 2698:八皇后问题

OpenJ_Bailian - 2698:八皇后问题

标签:

来源:

参考资料:

相似题目:

题目

按给定顺序和格式输出所有八皇后问题的解(见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
……

解题思路

参考代码

#include
#include
#include
int board[10];
int n=8,cnt; 

void print_queen(int *board)
{
    //原题目输出的结果行列互换 
    printf("No. %d\n",cnt);
    for(int j=0;j<8;j++)
    {
        for(int i=0;i<8;i++)
        {
            if(board[i]==j)printf("1 ");
            else printf("0 ");
        }
        printf("\n");
    }
//  system("pause");
} 

void search(int row)
{
    if(row==n)
    {
        cnt++;
        print_queen(board); 
    }
    else for(int i=0;ibool judge=true;
        board[row]=i;//尝试把第cur行的皇后放在第i列 
        for(int j=0;j//检查是否和前面的皇后冲突(主对角线用y-x标识,副对角线用x+y标识) 
            if(board[row]==board[j] || row-board[row]==j-board[j] || row+board[row]==j+board[j])
            {
                judge=false;
                break;
            }
        if(judge==true)
            search(row+1);
    }
}

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

你可能感兴趣的:(【记录】算法题解)