八皇后问题(递归)

问题描述

       八皇后问题,是一个古老而著名的问题,是回溯算法的典型案例。该问题是国际西洋棋棋手马克斯·贝瑟尔于1848年提出:在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法.

思路

       本题采用回溯递归求解,从第一行开始选择摆放位置,这样就避免了横向冲突,然后每次放置皇后只要检验是否存在纵向冲突或斜向冲突。

code
#include <iostream>
using namespace std;

const int n = 8;

int result[10];
int cnt;

void slove(int cur)
{

    if(cur == n)
    {
        //打印结果
        cout << "#" << cnt ++ << ": "; 
        for(int i = 0; i < n; i ++)
        {
            cout << "(" << i << ", " << result[i] << ") ";
        }
        cout << endl;
    }
    else
    {
        for(int i = 0; i < n; i ++)
        {
            //选择在第cur行第列放置
            result[cur] = i;
            bool ok = true;
            for(int j = 0; j < cur; j ++)
            {
                //检测是否与之前放置的皇后存在斜向或者纵向冲突
                if(result[cur]-result[j] == cur-j || result[j]-result[cur] == cur-j || result[cur] == result[j] )
                {
                    ok = false;
                    break;
                } 
            }
            if(ok)
            {
                //没冲突时递归向下一行求解
                slove(cur+1);
            }
        }

    }
}

int main()
{
    slove(0);
    return 0;
}

转载于:https://www.cnblogs.com/topk/p/6580099.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java八皇后问题是一个经典的回溯算法问题,目标是在一个8x8的棋盘上放置8个皇后,使得它们互相之间不能攻击到对方。在这个问题中,皇后可以攻击同一行、同一列以及同一对角线上的其他皇后。 递归是解决八皇后问题的常用方法之一。下面是一个简单的Java代码示例: ```java public class EightQueens { private static final int SIZE = 8; private static int[] queens = new int[SIZE]; public static void main(String[] args) { solve(0); } private static void solve(int row) { if (row == SIZE) { printQueens(); return; } for (int col = 0; col < SIZE; col++) { if (isValid(row, col)) { queens[row] = col; solve(row + 1); } } } private static boolean isValid(int row, int col) { for (int i = 0; i < row; i++) { if (queens[i] == col || queens[i] - col == i - row || queens[i] - col == row - i) { return false; } } return true; } private static void printQueens() { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { if (queens[i] == j) { System.out.print("Q "); } else { System.out.print(". "); } } System.out.println(); } System.out.println(); } } ``` 在这段代码中,我们使用一个一维数组`queens`来表示每一行皇后所在的列数。`solve`方法是递归的核心部分,它尝试在当前行的每一列放置皇后,并递归地调用下一行。`isValid`方法用于判断当前位置是否可以放置皇后,它检查同一列、同一对角线上是否已经存在皇后。当放置完最后一行的皇后时,我们就找到了一个解,通过`printQueens`方法打印出棋盘。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值