LeetCode: N-Queens

来源:互联网 发布:java unicode编码转换 编辑:程序博客网 时间:2024/05/16 19:53

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


class Solution {public:    vector<vector<string> > solveNQueens(int n) {        vector<int> index(n, -1);        jump(index, 0, n);        return result;    }private:    vector<vector<string> > result;    void print(vector<int> &index, int n)    {        vector<string> temp;        for(int i = 0; i < n; i++)        {            string cur;            for(int j = 0; j < n; j++)            {                if(index[i] == j)                    cur += 'Q';                else                {                    cur += '.';                }            }            temp.push_back(cur);            cur.clear();        }        result.push_back(temp);            }    void jump(vector<int> &index, int x, int n)    {        if(x == n)            print(index, n);        for(int i = 0; i < index.size(); i++)        {            if(isValid(index, x, i))            {                index[x] = i;                jump(index, x+1, n);            }        }    }    bool isValid(vector<int> &index, int x, int y)    {        for(int i = 0; i < x; i++)        {            if(index[i] == y || std::abs(index[i] - y) == x-i)                return false;        }        return true;    }};


Round 2:

class Solution {public:    vector<vector<string> > solveNQueens(int n) {        vector<vector<string> > result;        if(n == 0)            return result;        string temp(n, '.');        vector<string> cur(n, temp);        vector<int> marked(n, -1000);        dfs(result, cur, marked, 0);        return result;    }private:    void dfs(vector<vector<string> > &result, vector<string> &cur, vector<int> &marked, int row)    {        if(row == marked.size())        {            result.push_back(cur);            return;        }        for(int col = 0; col < marked.size(); col++)        {            int flag = 0;            for(int i = 0; i < row; i++)            {                if(marked[i] == col || marked[i] == col+row-i || marked[i] == col-row+i)                {                    flag = 1;                    break;                }            }            if(flag)                continue;            marked[row] = col;            cur[row][col] = 'Q';            dfs(result, cur, marked, row+1);            marked[row] = -1000;            cur[row][col] = '.';        }    }};








0 0