leetcodeOJ 51. N-Queens

来源:互联网 发布:开罗旅游自助攻略知乎 编辑:程序博客网 时间:2024/06/07 14:18

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


利用回溯方法,逐行放置QUEEN,假设需在第i行确定皇后位置,那么放之前先确认把皇后放在这个位置是合法的,所谓合法即不冲突,也就是说在同一列、45度角和135度角上,第0行到第i-1行并没有皇后。

代码如下:

class Solution {public:    vector<vector<string>> solveNQueens(int n) {        vector<vector<string>> ans;                vector<string> re(n, string(n, '.'));        genNQueens(ans, re, 0, n);        return ans;    }    private:    void genNQueens(vector<vector<string>>& ans, vector<string>& re, int srt, int end){        if(srt == end){            ans.push_back(re);            return;        }        for(int i = 0; i < end; i++){            if(isValid(re, srt, i, end)){                re[srt][i] = 'Q';                genNQueens(ans, re, srt+1, end);                re[srt][i] = '.';            }        }    }        bool isValid(vector<string>& re, int row, int col, int n){        for(int i = 0; i < row; i++){            if(re[i][col] == 'Q')                return false;        }        for(int i = row-1, j = col-1; i >= 0 && j >= 0 ; i--, j--){            if(re[i][j] == 'Q')                return false;        }        for(int i = row-1, j = col+1; i >= 0 && j < n; i--, j++){            if(re[i][j] == 'Q')                return false;        }                return true;    }};


0 0
原创粉丝点击