我有这个类来保存两个值:
public class Coord {
public int x;
public int y;
public Coord(int x, int y) {
this.x = x;
this.y = y;
}
}
我正在尝试在深度优先搜索算法中使用它:
x = this.move_to_x;
y = this.move_to_y;
Coord stack = new Coord(0, 0);
Stack<Coord> start = new Stack<Coord>();
Stack<Coord> visited = new Stack<Coord>();
start.push(stack);
visited.push(stack);
while (!start.empty()) {
Coord tmp = (Coord)start.pop();
int j,k;
j = tmp.x;
k = tmp.y;
// there is only 8 possible ways to go (the neighbors)
for (int a = -1; a < 2; a++) {
tmp.x = j + a;
for (int b = -1; b < 2; b++) {
if (a == 0 && b == 0) {
continue;
}
tmp.y = k + b;
if (tmp.x < 0 || tmp.y < 0) {
continue;
}
if (tmp.x > 5 || tmp.y > 5) {
continue;
}
if (tmp.x == x && tmp.y == y) {
System.out.println("end!");
return;
}
Coord push = new Coord(tmp.x, tmp.y);
System.out.println("visited: " + visited);
if (visited.search(push) == -1) {
System.out.println("added x " + push.x + " y " + push.y
+ " " + visited.search(push));
start.push(push);
visited.push(push);
} else {
System.out.println("visited x " + tmp.x + " y " + tmp.y
+ " index " + visited.search(push));
}
}
}
}
问题是该visited.search
方法总是返回-1
。这是日志:
visited: [Agent.ExampleAgent.Coord@1af6a711]
added x 0 y 1 -1
visited: [Agent.ExampleAgent.Coord@1af6a711, Agent.ExampleAgent.Coord@1c727896]
added x 1 y 0 -1
visited: [Agent.ExampleAgent.Coord@1af6a711, Agent.ExampleAgent.Coord@1c727896, Agent.ExampleAgent.Coord@5fbd8c6e]
added x 1 y 1 -1
visited: [Agent.ExampleAgent.Coord@1af6a711, Agent.ExampleAgent.Coord@1c727896, Agent.ExampleAgent.Coord@5fbd8c6e, Agent.ExampleAgent.Coord@427a8ba4]
added x 0 y 0 -1
visited: [Agent.ExampleAgent.Coord@1af6a711, Agent.ExampleAgent.Coord@1c727896, Agent.ExampleAgent.Coord@5fbd8c6e, Agent.ExampleAgent.Coord@427a8ba4, Agent.ExampleAgent.Coord@262f6be5]
added x 0 y 1 -1
visited: [Agent.ExampleAgent.Coord@1af6a711, Agent.ExampleAgent.Coord@1c727896, Agent.ExampleAgent.Coord@5fbd8c6e, Agent.ExampleAgent.Coord@427a8ba4, Agent.ExampleAgent.Coord@262f6be5, Agent.ExampleAgent.Coord@199d4a86]
请注意,添加到已访问堆栈的第一个元素是(0,1)
,但是当搜索它时(0,1)
,该方法稍后会返回-1
。