给你一个无穷大的网格图。一开始你在 1 1 你需要通过有限步移动到达点 targetX targetY 。每一步 你可以从点 x y 移动到以下点之一:x y - xx - y y2 x yx 2 y给你两个整数 targetX 和 targetY 分别表示你最后需要到达点的 X 和 Y 坐标。如果你可以从 1 1 出发到达这个点请你返回true 否则返回 false 。请提供代码
可以使用广度优先搜索算法来解决这个问题。
首先定义一个点的类 Point,包含两个属性 x 和 y,以及一个构造函数和重写 equals 和 hashCode 方法。
然后定义一个 canReach 方法,使用队列实现广度优先搜索。从起点 (1, 1) 开始,依次尝试四个移动方式得到下一个点,如果下一个点不在已经走过的路径中且不超出边界,则将该点加入队列中。直到队列为空或者找到目标点为止。
Java 代码如下:
class Point { int x; int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Point) {
Point other = (Point) obj;
return this.x == other.x && this.y == other.y;
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(this.x, this.y);
}
}
public boolean canReach(int targetX, int targetY) {
Queue
Point start = new Point(1, 1);
queue.offer(start);
visited.add(start);
while (!queue.isEmpty()) {
Point current = queue.poll();
if (current.x == targetX && current.y == targetY) {
return true;
}
Point next1 = new Point(current.x, current.y - current.x);
Point next2 = new Point(current.x - current.y, current.y);
Point next3 = new Point(current.x * 2, current.y);
Point next4 = new Point(current.x, current.y * 2);
if (next1.x > 0 && next1.y > 0 && !visited.contains(next1)) {
queue.offer(next1);
visited.add(next1);
}
if (next2.x > 0 && next2.y > 0 && !visited.contains(next2)) {
queue.offer(next2);
visited.add(next2);
}
if (next3.x > 0 && next3.y > 0 && !visited.contains(next3)) {
queue.offer(next3);
visited.add(next3);
}
if (next4.x > 0 && next4.y > 0 && !visited.contains(next4)) {
queue.offer(next4);
visited.add(next4);
}
}
return false;
原文地址: https://www.cveoy.top/t/topic/egV0 著作权归作者所有。请勿转载和采集!