跳至正文
-
Subscribe to our newsletter & never miss our best posts. Subscribe Now!
小奥的学习笔记

万丈高楼平地起,勿在浮沙筑高台

小奥的学习笔记

万丈高楼平地起,勿在浮沙筑高台

  • 首页
  • Sample Page
  • 隐私策略
  • GuestBook
  • 慕课课程(MOOC’s Lessons)
  • Footprints
  • About Me
  • 个人履历
  • 首页
  • Sample Page
  • 隐私策略
  • GuestBook
  • 慕课课程(MOOC’s Lessons)
  • Footprints
  • About Me
  • 个人履历
关

搜索

  • https://www.facebook.com/
  • https://twitter.com/
  • https://t.me/
  • https://www.instagram.com/
  • https://youtube.com/
Subscribe

n queens ii

题目描述

Follow up for N-Queens problem.Now, instead outputting board configurations, return the total number of distinct solutions.

题目解析

我们令x[i]的值为第i个皇后所在的列数。那么我们第一个皇后的位置可以在第一行任意一个位置任选,所以我们试出来第一个皇后在第1到第n个列位置下的不同情况(一共有n颗n叉树)。然后安排完第一个皇后位置后,第二个皇后位置在第二行也是从第1到第n列分别试一遍,看是否满足要求。若满足要求则进行第三个皇后,否则该树是没有结果的。当不断递归到t>n的时候,那说明在上一步已经安排完了,那么久直接对计数加1,然后返回。

void Backtrack(int t,int num)
    {
        if(t>num)
        {
            countn++;
        }
        else
            for(int i=1;i<=num;i++)
            {
                x[t]=i;
                if(Place(t))
                    Backtrack(t+1,num);
            }
    }void Backtrack(int t,int num)
    {
        if(t>num)
        {
            countn++;
        }
        else
            for(int i=1;i<=num;i++)
            {
                x[t]=i;
                if(Place(t))
                    Backtrack(t+1,num);
            }
    }

题目要求就是每一个皇后不能跟上一行的那个皇后同一列和对角线,所以在获得下一列真实的位置的时候,需要判断是不是在同一列或者对角线,即:

bool Place(int t)
    {
        bool ok=true;
        for(int j=1;j<t;j++)
        {
            if(x[t]==x[j]||t-j==fabs(x[t]-x[j]))//判断列对角线是否冲突
            {
                ok=false;
                break;
            }
        }
        return ok;
    }

代码实现

public:
    int countn=0;
    int x[200];
    bool Place(int t)
    {
        bool ok=true;
        for(int j=1;j<t;j++)
        {
            if(x[t]==x[j]||t-j==fabs(x[t]-x[j]))//判断列对角线是否冲突
            {
                ok=false;
                break;
            }
        }
        return ok;
    }

    void Backtrack(int t,int num)
    {
        if(t>num)
        {
            countn++;
        }
        else
            for(int i=1;i<=num;i++)
            {
                x[t]=i;
                if(Place(t))
                    Backtrack(t+1,num);
            }
    }
    int totalNQueens(int n) {
        Backtrack(1,n);
        return countn;
    }

标签:

leetcode
作者

yszhang

关注我
其他文章
上一个

济南市生态环境局关于作出《济莱高铁项目前期工作筹备组新建济南至莱芜高速铁路项目环境影响报告书》审批决定的公告

下一个

[Leetcode]merge sorted array

暂无评论!成为第一个。

发表回复 取消回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Copyright 2026 — 小奥的学习笔记. All rights reserved. Blogsy WordPress Theme