骑士之旅问题编译未完结

问题描述

谁能指出代码中的缺陷? 我使用的想法是通过递归进行回溯,我想坚持这种解决给定问题的方式。当变量移动

//checking on which move was the square visited
int board[8][8] = {{1,0},{0,0}};
int x = 0;//x and y coordinate of the knight's placement
int y = 0;
//move knight by
int move_to[8][8] = {{1,2},{-1,-2},{1,{2,1},{-2,-1},-1}};
//how many moves have been done
int moves = 0;

void solve()
{
    //printing one solution
    if(moves==63)
    {
        for(int k = 0; k < 8; k++)
        {
            for(int n = 0; n < 8; n++)
                cout << setw(2) << board[k][n] << " ";
            cout << "\n";
        }
        cout << "--------------------\n";
        return;
    }
    else
    {
     for(int i = 0; i < 8; i++)
    {
        //checking if knight is not leaving the board
        if(x+move_to[i][0]<0 || x+move_to[i][0]>7 || y+move_to[i][1]<0 ||
            y+move_to[i][1]>7 || board[x+move_to[i][0]][y+move_to[i][1]]>0)
            continue;
        //moving theknight
        x+=move_to[i][0];
        y+=move_to[i][1];
        //increasing the moves count
        moves++;
        //marking the square to be visited
        board[x][y] = moves+1;
        //backtracking
        solve();
        board[x][y] = 0;
        x-=move_to[i][0];
        y-=move_to[i][1];
        moves--;
    }
    }
}

int main()
{
    solve();

    return 0;
}

解决方法

我在学习中记得这个问题。我没有修复它们,但我改变了初始位置,然后更快地找到了第一条路径(这就是我通过这个实验室的方式;P)。这是正常的,因为 路径数太大。

但你可以:

  • 以随机顺序从 move_to 中选择
  • 使用多个线程

另一方面,您可以阅读“约束编程”