N皇后问题的局面个数 N-Queens II

来源:互联网 发布:javascript代码规范 编辑:程序博客网 时间:2024/03/29 00:41

对于N皇后问题,有多少种可能的局面呢?

温习一下backtrack吧。


代码:

class Solution {public:    bool isValid(int board[], int n, int row, int col)    {        for(int i=0;i<row;i++) //判断当前位置(row, col)是否和之前行的元素有冲突        {            if(board[i] == col)                return false;            if(abs(board[i] - col) == abs(i - row)) //行跟行之差 == 列跟列之差                return false;        }        return true;    }        void fun(int board[],int n, int row)    {        if(row == n)        {            count++;            return;        }        for(int i=0;i<n;i++)        {            if(isValid(board, n, row, i))            {                board[row] = i;                fun(board, n, row+1);            }        }    }        int count = 0;        int totalNQueens(int n) {        int board[n];        memset(board, 0, sizeof(board));        fun(board, n, 0);        return count;    }};


0 0
原创粉丝点击