• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
51. N-Queens 52. N-Queens II *HARD*

1. 求所有解

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.."]
]
void insert(vector<vector<string>> &ans, vector<int> q, int n)
{
    vector<string> v(n, string(n, '.'));
    for(int i = 0; i < n; i++)
        v[i][q[i]] = 'Q';
    ans.push_back(v);
}
void helper(vector<vector<string>> &ans, vector<int> q, int n, int k)
{
    if(k == n)
    {
        insert(ans, q, n);
        return;
    }
    int i, j;
    for(i = 0; i < n; i++)
    {
        for(j = 0; j < k; j++)
        {
            if(q[j] == i || abs(j-k) == abs(q[j]-i))
                break;
        }
        if(j < k)
            continue;
        q[k] = i;
        helper(ans, q, n, k+1);
    }
}
vector<vector<string>> solveNQueens(int n) {
    vector<vector<string>> ans;
    vector<int> q(n, -1);
    for(int i = 0; i < n; i++)
    {
        q[0] = i;
        helper(ans, q, n, 1);
    }
    return ans;
}

 

2. 求解的个数

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

void helper(int &ans, vector<int> q, int n, int k)
{
    if(k == n)
    {
        ans++;
        return;
    }
    int i, j;
    for(i = 0; i < n; i++)
    {
        for(j = 0; j < k; j++)
        {
            if(q[j] == i || abs(j-k) == abs(q[j]-i))
                break;
        }
        if(j < k)
            continue;
        q[k] = i;
        helper(ans, q, n, k+1);
    }
}
int totalNQueens(int n) {
    int ans = 0;
    vector<int> q(n, -1);
    for(int i = 0; i < n; i++)
    {
        q[0] = i;
        helper(ans, q, n, 1);
    }
    return ans;

 

posted on 2016-03-11 15:28  ArgenBarbie  阅读(204)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3