java - 如何在 Java 中解决这个国际象棋骑士问题?
问题描述
我想使用 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++;
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);
}
}
谢谢!
解决方案
我想问题是你if (aVisited == now)
在你的hasNotVisited
方法中使用。你需要if (aVisited.equals(now))
。
- 使用时,
==
您正在检查两个变量是否引用Vector
. - 使用时,
.equals
您正在检查它是否涉及Vector
具有相同属性/值的两个。
编辑:我只是注意到Vector
不会覆盖equals
. 另请参阅 的源代码Vector
。或者,您可以(if aVisited.x == now.x && aVisited.y == now.y)
在您的hasNotVisited
方法中使用。
推荐阅读
- android - 为什么这个 kotlin 分配可能(switchButton.isChecked = true)
- c - 编程C的执行结果并不顺利。为什么?
- python - 获取scipy的solve_ivp函数执行中间任务
- sql-server - 对于 sql server,我想选择所有已更改的记录
- python - Google App Engine 不为我在 app.yaml 中定义的入口点提供服务
- sql - 在 Postgresql 中将 UUlD 存储为 VARCHAR 而不进行任何格式化
- mobaxterm - 如何在 Mobaxterm 上使用自定义语法高亮
- amazon-web-services - Glue Boto 客户端——NoCredentialsError
- java - 如何在 android 上创建复制链接地址菜单?
- r - 使用 dplyr 查找列中的最大值并从不同列返回元素