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

问题描述 投票:0回答:1

我想用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);
    }
}

谢谢!

java logic
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.