如何用Java解决这个国际象棋骑士问题?

时间:2018-11-06 19:37:53

标签: java logic

我想使用Java解决国际象棋难题。我编码为Knight片段从开始字段(1; 1)移动到任何地方,除了负的x和y之外,如果所有内容都有效,则将此访问字段放入列表中,否则返回上一个字段。但这根本不起作用,这种情况永远不会成立,它一直都是负数,并且不会回到上一个字段,这可能是什么原因引起的?

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Main
{
    static Vector now;
    static Vector prev;

    static List<Vector> visited = new ArrayList<>();

    public static void main(String[] args)
    {
        now = new Vector(); // sets x = 1, y = 1
        prev = now; // also x = 1, y = 1

        visited.add(now); // we are already on (1;1)

        generate();
    }

    static void generate()
    {
        Random rand = new Random();

        for (int i = 0; i < 50; i++)
        {
            int a = rand.nextInt(8);
            move(a);

            if((isValid()) && hasNotVisited()) // if x and y > 0 , because the smallest coord is (1;1), and check is we haven't visited that field
            {
                visited.add(now);
                prev = now; // previous coord is now, then make a new step
            }
            else
            {
                now = prev; // else, return to previous coord
                // For example, we are one (3;2), we move to (1;0), that's not valid, we should move back to (3;2)
            }
        }
    }

    static void move(int a)
    {
        switch (a){
            case 0:
                now.x += 2;
                now.y++;
                break;
            case 1:
                now.x += 2;
                now.y--;
                break;
            case 2:
                now.x -= 2;
                now.y++;
                break;
            case 3:
                now.x -= 2;
                now.y--;
                break;
            case 4:
                now.y += 2;
                now.x++;
                break;
            case 5:
                now.y += 2;
                now.x--;
                break;
            case 6:
                now.y -= 2;
                now.y++;
                break;
            case 7:
                now.y -= 2;
                now.y--;
                break;
        }
    }

    static boolean hasNotVisited()
    {
        for (Vector aVisited : visited) {
            if (aVisited == now)
                return false;
        }

        return true;
    }

    static boolean isValid()
    {
        return (0 < now.x && now.x <= 10) && (0 < now.y && now.y <= 10);
    }
}

谢谢!

1 个答案:

答案 0 :(得分:1)

我想问题是您在if (aVisited == now)方法中使用了hasNotVisited。您需要if (aVisited.equals(now))来代替。

  • 使用==时,您要检查两个变量是否引用了Vector的同一实例。
  • 使用.equals时,您要检查它是否涉及两个Vector 具有相同的属性/值。

编辑:我刚刚注意到Vector不会覆盖equals。另请参见source code of Vector。另外,您可以在(if aVisited.x == now.x && aVisited.y == now.y)方法中使用hasNotVisited