如果语句导致程序因递归而崩溃

我正在尝试让我的程序为AI扫描棋盘以寻找移动方式。如果我只使用第一个if语句,它能够正常工作,但当我添加else if语句时,程序就会崩溃。

void BoardSet::foxNextToSheep(int x, int y, int& moves){    if(board[x+1][y] == 'S' && board[x+2][y] == '.')     {        x = x + 2;        moves++;        foxNextToSheep(x, y, moves);    }    else if(board[x-1][y] == 'S' && board[x-2][y] == '.')    {        x = x - 2;        moves++;        foxNextToSheep(x, y, moves);    }}

我猜测这是由于递归引起的,有没有更好的方法来实现这个功能?

我意识到问题出在board[x-1][y]会导致x变为负数而无法正常工作。有没有办法阻止这种情况发生?

class BoardSet {public://Functions used for foxes    bool findFox(int x, int y);    void foxNextToSheep(int x, int y, int& moves);private:     char board[7][8];    int sheep;    int foxes;};class Foxes {public:void foxesProcess(BoardSet& board);void findFoxes(BoardSet& board);void checkForPossibleMoves(BoardSet& board);void print();private:    int foxes[2][2];};void Foxes::checkForPossibleMoves(BoardSet& board){    int moves1 = 0;    int foxOneX = foxes[0][0];    int foxOneY = foxes[0][1];    board.foxNextToSheep(foxOneX, foxOneY, moves1);    cout << moves1 << endl;}

调用检查移动的函数

void Foxes::foxesProcess(BoardSet& board){    cout << "The foxes move: ";    findFoxes(board);    checkForPossibleMoves(board);}

从主函数中

void processGame(istream& in){    int repeat = 1;    BoardSet board;    Sheep sheep;    Foxes foxes;    initalizeBoard(in, board);    while(repeat)    {        board.checkForWin(repeat);        if(repeat == 0)            break;        sheep.sheepProcess(board);        board.print();        board.checkForWin(repeat);        if(repeat == 0)            break;        foxes.foxesProcess(board);    }}

回答:

你的函数中没有进行边界检查,因此假设board只是一个标准数组或一个不进行边界检查的类,那么当x<=1时,你将超出边界并进入未定义行为。

在没有看到更多代码的情况下,最明显的检查和修复方法是这样的:

else if( x > 1 && (board[x-1][y] == 'S' && board[x-2][y] == '.') )

你也在if语句中存在边界检查问题,如果x >= 4,你也会超出边界:

if( x <= 4 && (board[x+1][y] == 'S' && board[x+2][y] == '.') ) 

如果决定更改边界,拥有一个定义最大值的变量会很有帮助。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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