骑士之旅算法

时间:2015-04-10 09:28:39

标签: c#

我是编程新手,我想解决骑士之旅作为练习。 但我不明白我的程序错误在哪里 这是我的方法:

 class Knight
{
    int N, M;
    bool[,] board ;

    public Knight()
    {
        N = 5;
        board = new bool[N, N];
        N *= N;
        M = N - 1;
    }



    public bool Movement(int y, int x, int mov)
    {

        if (x < 0 || x >= 5 || y < 0 || y >= 5) 
        {
            return false;
        }
        if (board[x, y] == true) // has been in that position
        {
            return false ;
        }
        if (mov == M)
        {
            Console.WriteLine("Solution");
            board[x, y] = true;
            return true;
        }
        else
        {

           bool result = false;

             result = result || Movement( x+2, y+1, mov+1);
             result = result || Movement( x+2, y-1, mov+1);
             result = result || Movement( x-2, y+1, mov+1);
             result = result || Movement( x-2, y-1, mov+1);
             result = result || Movement( x+1, y+2, mov+1);
             result = result || Movement( x+1, y-2, mov+1);
             result = result || Movement( x-1, y+2, mov+1);
             result = result || Movement( x-1, y-2, mov+1);

             if (result == true)
             {
                 Console.WriteLine("{0} {1}", x, y);

                 return true;
             }
             else
             {

                     board[x, y] = false;
                     return false;

             }
        }
    }

我不知道为什么我会重复坐标 这是输出:

2 1
3 1
3 4
2 4
2 1
3 1
3 4
2 4
2 1
3 1
3 4
2 4
2 1
3 1
3 4
2 4
2 1
3 1
3 4
2 2
4 1
3 3
1 2
0 0

1 个答案:

答案 0 :(得分:0)

我认为你没有设置

board[x, y] = true;

在你的情况下,以防

if (result == true)