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.."]

]

 

        思路:本题又是一个典型的回溯法题型,采用递归方法解决。在第i行找到一个有效的位置后,接着递归深入到第i+1行寻找有效的位置,如果能找到,则继续深入;如果找不到,则回退到第i行,继续寻找第i行另一个有效位置。只要在最后一行找到一个有效位置,则表明找到了一个合格的答案。然后接着寻找最后一行下一个有效位置即可。

        因为是以行数从上到下进行深入的,所以在判断有效位置的时候,只需要判断到当前行即可。

        返回结果需要放到一个数组中,每个数组元素就是一个“棋盘”。因事先无法预料有多少个解法,需要边寻找边计数,所以本算法首先将所有结果放到一个链表中,然后在将链表复制到数组中。代码如下:

 

typedef struct queennode
{
    char **board;
    struct queennode *next;
}QueenNode;
 
int isvalidqueen(char**board, int line, int col, int n)
{
    int i, j;
 
    for(i = 0; i <line; i++)
    {
        if(board[i][col]== 'Q')    return 0;
    }
 
    for(i = line-1,j = col-1; i>=0 && j>=0;i--,j--)
    {
        if(board[i][j]== 'Q')  return 0;
    }
 
    for(i = line-1,j = col+1; i>=0 && j<n;i--,j++)
    {
        if(board[i][j]== 'Q')  return 0;
    }
 
    return 1;
}
 
QueenNode *copyboard(char**board, int n)
{
    int i;
    QueenNode *res = calloc(1,sizeof(QueenNode));
    res->board = calloc(n,sizeof(char *));
 
    for(i = 0; i <n; i++)
    {
        res->board[i] =calloc(n, sizeof(char));
        memcpy(res->board[i],board[i], n*sizeof(char));
    }
    return res;
}
 
void nqueencore(char**board, int line, int n, QueenNode **head,int *listlen)
{
    int i;
    QueenNode *res;
    for(i = 0; i <n; i++)
    {
        if(isvalidqueen(board,line, i, n))
        {
            board[line][i]= 'Q';
            if(line == n-1)
            {
                res = copyboard(board,n);
                res->next = *head;
                *head = res;
                *listlen += 1;
            }
            else
            {
                nqueencore(board,line+1, n, head, listlen);
            }  
            board[line][i]= '.';
        }
    }
}
 
 
char*** solveNQueens(intn, int* returnSize)
{
    char **board = calloc(n,sizeof(char *));
    int i, j;
    int reslen = 0;
    char ***res;
    for(i = 0; i <n; i++)
    {
        board[i] = calloc(n,sizeof(char));
        memset(board[i], '.',n);
    }
 
    QueenNode *head = NULL;
    QueenNode *p = NULL;
    QueenNode *q = NULL;
 
    nqueencore(board, 0, n,&head, &reslen);
    res = calloc(reslen, sizeof(char**));
 
    for(i = 0, p = head;i < reslen && p != NULL; i++)
    {
        res[i] = p->board;
        q = p;
        p = p->next;
        free(q);
    }
    *returnSize = reslen;
 
    return res;
}

 

posted @ 2015-08-22 15:25  gqtc  阅读(144)  评论(0)    收藏  举报