0

我创建了一个专门为此目的处理 2d 向量的类 Board。我正在尝试解决骑士之旅。我想在完成后打印出来。使用递归 voyagingKnight() 函数,我发现它没有做任何事情,也没有打印结果。似乎我想增加递归调用的步骤号,但这不起作用。

向量参数 incs 是用于移动马的 2d 增量向量,在每一行中,第一列中移动一行,第二列中移动一列。

有人对我在这里推理的缺陷有任何建议吗?相关代码

    bool voyaging_knight( Board &board, int i, int j, int steps ,vector< vector<int> > &increments)
    {
        if( !newplace(theboard, i, j) ) return false; 
        board.setval(i,j,step);

        if( gone_everywhere( board, steps) )
        {
        cout <<"DONE" << endl; 
        board.showgrid();
         return true; 
        }   

        int n;
        int in, jn;   
        for(n=0; n<8; n++ )
        {
            in = i + increments[n][0]; 
            jn = j + increments[n][1]; 

            if( inboard(board, i, j)&& newplace(board,i,j) )
            {

             voyaging_knight( board, in, jn, steps+1 ,increments);

            return true; 
            }
        }


        theboard.setval(i,j,-1); 

    }
4

3 回答 3

0

使棋盘成为全局变量,并在全局变量中构建一系列访问过的方块。确保在撤回每个暂定步骤时撤消任何更改(已访问的正方形,序列的最后一步)。调用你的骑士的游览函数,如果到达终点则返回成功,并在完成后进行任何输出。

将整个 shebang 打包在一个文件中或作为一个类,以免将私人细节暴露给窥探。

于 2014-03-08T16:35:36.590 回答
0

I'm guessing that you want 1 continuous path made by horse movements on a (chess)-board found by backtracking. In that case you have to pass the board by value, so each path you take has its own instance to fill. By passing by reference, every path fills the same board, so you can never take all the steps.

Also you should pass a result by value and fill it with the positions you visited and return that from the recursive function, so each path has its own instance of resulting positions and by returning it, you end up with the final result.

You should not pass inc because that is just a helper container that doesn't change.

于 2014-03-05T09:13:55.553 回答
0

是的,改变这个:

voyagingKnight( theboard, inext, jnext, step+1 ,incs);
return true; 

对此:

return voyagingKnight( theboard, inext, jnext, step+1 ,incs);

此外,您似乎需要false在函数末尾返回一些东西(可能)。

顺便说一句,我假设您已将所有条目theboard初始化为-1.

于 2014-03-05T09:01:43.317 回答