简体   繁体   English

C ++和python在AugustQueens上的结果不同

[英]Different result on EightQueens in C++ and python

I encountered a problem in solving the eight queen problems. 我在解决八个皇后问题时遇到了一个问题。 I first wrote the following code in C++. 我首先用C ++编写了以下代码。

#include <iostream>
#include <cmath>
using namespace std;
bool flag=true;
void queen(int *arr,int n,int cnt){
    if(cnt==n){
        for(int i=0;i<n;i++){
            cout<<arr[i]<<" ";
        }
        return;
    }
    for(int col=0;col<n;col++){
        arr[cnt]=col;
         flag=true;
         for(int row=0;row<cnt;row++){
             if(arr[row]==col||(abs(col-arr[row])==cnt-row)){
                 flag=false;
                 break;
             }
         }
         if(flag){
             cnt++;
             queen(arr,n,cnt);
         }
    }
}

int main() {
    int n=8;
    int arr[n]={0};
    queen(arr,n,0);
}

This should get correct results,but nothing is output.So I wrote the simpler code in python with the same idea as follows. 这应该得到正确的结果,但是什么也没有输出。因此,我用以下相同的思想在python中编写了更简单的代码。

count=0
def queen(A, cnt=0):
    global count
    if cnt == len(A):
        print(A)
        count+=1
        return 0
    for col in range(len(A)):
        A[cnt], flag = col, True
        for row in range(cnt):
            if A[row] == col or abs(col - A[row]) == cnt - row:
                flag = False
                break
        if flag:
            queen(A, cnt+1)
queen([None]*8)
print(count)

This time I got the correct answer. 这次我得到了正确的答案。 I don't think any difference between these two codes. 我认为这两个代码之间没有任何区别。 I was wondering someone could point out what's wrong with the c++ codes. 我想知道有人能指出C ++代码出了什么问题。

[0, 4, 7, 5, 2, 6, 1, 3]
[0, 5, 7, 2, 6, 3, 1, 4]
[0, 6, 3, 5, 7, 1, 4, 2]
[0, 6, 4, 7, 1, 3, 5, 2]
[1, 3, 5, 7, 2, 0, 6, 4]
......
[7, 1, 4, 2, 0, 6, 3, 5]
[7, 2, 0, 5, 1, 4, 6, 3]
[7, 3, 0, 2, 5, 1, 6, 4]
92

I think this is the problem: 我认为这是问题所在:

     if(flag){
         cnt++;
         queen(arr,n,cnt);
     }

When you return cnt , is still incremented. 当您返回cnt ,仍会递增。 You want: 你要:

         queen(arr, n, cnt + 1);

which matches what happens in your Python version. 匹配您的Python版本中发生的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM