我试图用Java编写一个广度优先搜索的实现(不完整)但是当我尝试迭代所有相邻顶点到起始顶点时,我遇到了一个问题。
程序正在迭代所有相邻的顶点,但是当它到达if语句时,它检查是否已经访问过TargetVertex,它总是返回true而不是false,因此永远不会在括号内运行代码。
我不确定为什么会发生这种情况,因为在Vertex类中我已将所有新顶点的visited值初始化为false。有没有人看到我犯的错误或知道为什么会发生这种错误?我已经查看了所有其他方法/类,并且在任何时候都没有改变" visit"的值。任何帮助,将不胜感激!!
public void doBFS(String s){
//Create a queue
Queue<Vertex> q = new LinkedList<Vertex>();
//Create an arraylist to keep track of visited vertices
ArrayList<String> visited = new ArrayList<String>();
// Retrieve the starting vertex u, using the string name entered
Vertex u = vertices.get(s);
//Enqueue the starting node and add it to the visited set
visited.add(u.name);
u.visited = true;
u.distance = 0;
q.add(u);
while (! q.isEmpty() ) {
Vertex current = q.remove();
for (Edge e : current.getEdges()) {
//HERE IS THE PROBLEM. It always says it's true.
if(e.targetVertex.visited = false) {
visited.add(e.targetVertex.name);
q.add(e.targetVertex);
e.targetVertex.visited=true;
}
current = e.targetVertex;
}
}
}
我的Vertex类的开头:
public class Vertex {
public String name;
private List<Edge> adjacent;
public int posX = 0;
public int posY = 0;
public boolean visited = false;
public double distance = Double.POSITIVE_INFINITY;
/**
* Construct a new vertex containing an adjacency list.
*
* @param vertexName
* a unique identifier for this vertex.
* @param x
* the x coordinate for this vertex
* @param y
* the y coordinate for this vertex
*/
public Vertex(String vertexName, int x, int y) {
name = vertexName;
adjacent = new LinkedList<Edge>();
posX = x;
posY = y;
distance = Double.POSITIVE_INFINITY;
visited = false;
}
答案 0 :(得分:4)
if(e.targetVertex.visited = false) {
...是一项任务。使用
if(e.targetVertex.visited == false) {
......或者只是
if(!e.targetVertex.visited) {