Leetcode 51. N-Queens

题目

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]

分析

寻找N*N矩阵中放置N个皇后使其不会相互攻击的方案。使用回溯,一行一行的寻找可能的点,找到的话,继续找下一行,否则就退出。当找到一个可行的方案时候,需要将此时的二维数组的数据保存到最后的指针中。
C代码如下已通过:

int a[1000][1000];
//judge if(x,y)could be 1 in a[][]
bool place(int x,int y,int n)
{
    int i=0,j=0;
    for(i=0;i=0&&j>=0)
    {
        if(a[i][j]==1)return false;
        i--;j--;
    }
//search in right and top
    i=x-1;j=y+1;
    while(i>=0&&j

你可能感兴趣的:(Leetcode 51. N-Queens)