为什么下面的代码没有返回A,AEC,AEBCD?

时间:2017-05-14 19:29:43

标签: java search depth-first-search

我有一个深度限制搜索算法,我在循环中运行了几次,这样算法可以像迭代深化搜索算法一样, 为什么代码只在我明确调用方法时返回所需的结果,而不是在循环中调用它时。

string propertyName = ... // compose property name string according to your requirements
object propertyValue = Properties.Settings.Default[propertyName];

string stringRepresentationOfValue = Convert.ToString(propertyValue);

memoryToolStripMenuItem.DropDownItems[i].Text = stringRepresentationOfValue;

这是我的Graph类:

public class DepthLimited {

public static void main(String[] args) {
    Graph graph = new Graph();
    graph.addNode('A');    // Since A is the first vertex so it takes the index 0  
    graph.addNode('E');    // B is the second one so it takes index 1
    graph.addNode('B');    // index 2
    graph.addNode('C');    // index 3
    graph.addNode('D');    // index 4

    graph.addEdge(0, 1);     // This indicates the relation between the vertices A and E
    graph.addEdge(1, 2);     // This indicates the relation between the vertices E and B
    graph.addEdge(0, 3);     // This indicates the relation between the vertices A and C
    graph.addEdge(3, 4);     // This indicates the relation between the vertices C and D

 //        System.out.print("Sequence: ");
 //        graph.dls(2);
 //        System.out.println("");

    graph.dls(2); // produces AEBCD when called like this, before any other similar calls i.e graph.dls(1)

    for (int i = 0; i <= 2; i++) {
        graph.dls(i);  // when i is 2 the method only returns A instead of AEBCD
        System.out.println("");
    }
}
}

1 个答案:

答案 0 :(得分:0)

原因有两个。

首先,在调用checked后,每个访问者Node的{​​{1}}值都设置为true,并且在后续对该方法的调用中将保持这一值。您首先需要将它们设置为将dls(int limit)设置回checked

其次,false是一个类成员变量/字段,并且每次都不会重置为depth。该变量应该是方法的本地变量。

我建议您不要存储它们是作为0的属性访问,而是引入一个本地Node(例如Set)节点;或者在您的情况下,整数值表示访问过的HashSet对象的索引。

例如,快速攻击您的解决方案:

Node