gpt4 book ai didi

c - NxN 棋盘上的 N 个皇后

转载 作者:行者123 更新时间:2023-11-30 17:18:24 24 4
gpt4 key购买 nike

#include <stdio.h>
#include <math.h>

int n=4;
int GetQueenSettings(int board[4][4],int currentRow,int n)
{
//decide when the recursion stops
if(currentRow==n)
return 1; //successful setting
//otherwise we set column by column in this row and continue
int TotalSettingCount=0;
for(int i=0;i<n;i++)
{
//make sure it can be set (it is unset at that moment)
if(board[currentRow][i]==0)
{
board[currentRow][i]==1+currentRow;
//use row related info for settings
//now set invalid positions for remaining rows
setInvalid(board,currentRow,n,i);
//recover after this before trying the next
TotalSettingCount += GetQueenSettings(board,currentRow+1,n);
board[currentRow][i]=0;
RecoverBoard(board,currentRow,n);
}
}
return TotalSettingCount;
}

void setInvalid(int board[4][4],int currentRow,int n,int i)
{
//vertical and diagonal elements
for(int row=currentRow+1;row<n;row++) //start from the next line
{
//firstly make sure board can be set
if(board[row][i]==0)//vertical position
board[row][i]=-(1+currentRow);
//now check diagonal
int rowGap=row-currentRow;
if(i-rowGap>=0 && board[row][i-rowGap]==0)
{
//left bottom diagonal position
board[row][i-rowGap]=-(1+currentRow);
}
if(i+rowGap<n && board[row][i+rowGap]==0)
{
//bottom right diagonal position
board[row][i+rowGap]=-(1+currentRow);
}

}
}

void RecoverBoard(int board[4][4],int currentRow,int n)
{
//recover is to check all remaining rows if index is higher than current row(setters)
//OR less than -currentRow(invalids)!
for(int row=currentRow+1;row<n;row++)
{
for(int col=0;col<n;col++)
{
if(board[row][col]>currentRow || board[row][col]< -currentRow)
board[row][col]=0;
}
}
}
int main()
{

int board[n][n];
printf("Number of settings:-> %d",GetQueenSettings(board,0,n));

return 0;
}

NxN棋盘上放置了N个皇后,彼此互不干扰。当我运行此代码时,我得到的答案是 0 而不是 2 。我也无法找出将数组板传递给具有可变大小的函数的方法(大小将由用户给出)。我做错了什么?!

最佳答案

您应该初始化您的board 。事实上,你从一个充满垃圾值的棋盘开始。您正在使用可变长度数组作为板。此类数组无法初始化,因此您必须使用循环或 memset 将板设置为全零。来自<string.h> :

int board[n][n];

memset(board, 0, sizeof(board));

当维度作为早期参数传入时,您可以将可变长度数组传递给函数,例如:

int GetQueenSettings(int n, int board[n][n], int currentRow) { ... }

同时修复 =/==切换 setInvalid :

    if (board[row][i] == 0)
board[row][i] = -(1 + currentRow);

最后确保所有函数在调用时都有正确的原型(prototype)。

关于c - NxN 棋盘上的 N 个皇后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29185362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com