为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕婉清6462132 2022-01-06 17:00:34
我想使用 Java 解决国际象棋难题。我编码骑士块从开始字段 (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++;谢谢!
查看完整描述

1 回答

?
慕斯709654

TA贡献1840条经验 获得超5个赞

我想问题在于您正在使用if (aVisited == now)您的hasNotVisited方法。你需要if (aVisited.equals(now))代替。

  • 使用时,==您正在检查两个变量是否引用了Vector.

  • 使用时,.equals您正在检查它是否涉及Vector具有相同属性/值的两个。

编辑:我只是注意到Vector没有覆盖equals. 另请参阅 的源代码Vector。或者,您可以(if aVisited.x == now.x && aVisited.y == now.y)在您的hasNotVisited方法中使用。


查看完整回答
反对 回复 2022-01-06
  • 1 回答
  • 0 关注
  • 183 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号