51. N-Queens

来源:互联网 发布:宏业清单计价软件 编辑:程序博客网 时间:2024/05/21 22:55

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


1.我的解答  回溯


class Solution {public:        bool valid(vector<int> vec, int layer){        for(int i = 0; i < layer; i++){            if(vec[i] == vec[layer])                return false;        }        for(int i = 0; i < layer; i++){            if(abs(layer - i) == abs(vec[layer] - vec[i]))                return false;        }        return true;    }    void solve(vector<vector<int>>& result, vector<int>& vec, int n, int layer){        if(layer == n){            result.push_back(vec);            return;        }                for(int i = 0; i < n; i++){            vec[layer] = i;            if(valid(vec, layer)){                solve(result, vec, n, layer+1);            }        }    }    vector<vector<string>> solveNQueens(int n) {        vector<vector<string>>res;        if(n == 0) return res;        vector<vector<int>>result;        vector<int>vec(n,-1);        int layer = 0;        solve(result, vec, n, layer);        res.reserve(result.size());        string s;        for(int i = 0; i < n; i++)            s += ".";                for(int i = 0; i < result.size(); i++){            vector<string> str(n, s);            for(int j = 0; j < result[i].size(); j++){                str[j][result[i][j]] = 'Q';            }            res.push_back(str);        }        return res;    }};



2.有大神做到4ms的,下次再次刷的时候再看吧


0 0
原创粉丝点击