我正在实现类的广度优先和深度优先搜索,编译时出现我无法理解的错误。错误是:
符号:变量aList
位置:类java.lang.Object for(graphNode节点:map.get(i).aList){
aList 变量是一个 TreeSet,它存储在每个节点中,其中包含该节点在相应图中附加到的任何节点。我在上面的 main 方法中使用了完全相同的语法,它没有给出任何错误。此外,当我在 traverse 方法中打印出地图中的所有节点时,它打印的是整数键,而不是它应该具有的 graphNode 值。我现在很困惑。谢谢你的帮助。
import java.util.*;
import java.io.*;
public class HW1 {
public static void main (String[] args) throws Exception {
Scanner sc = new Scanner(new File(args[0]));
sc.useDelimiter("(\\s)"); // divide up by whitespcae
TreeMap<Integer, graphNode> map = new TreeMap<Integer, graphNode>();
int totalNodes = Integer.parseInt(sc.next());
int totalEdges = Integer.parseInt(sc.next());
// Fill up the map with nodes
for(int i = 1; i <= totalNodes ; i++) {
map.put(i, new graphNode(i, null, 10000));
}
// Add all the edges to the adjacency list
while(sc.hasNext()){
int start = Integer.parseInt(sc.next());
int end = Integer.parseInt(sc.next());
graphNode startNode = map.get(start);
graphNode endNode = map.get(end);
if(!startNode.aList.contains(endNode)){
startNode.aList.add(endNode);
}
if(!endNode.aList.contains(startNode)){
endNode.aList.add(startNode);
}
}
for(int i = 1; i <= map.size(); i++){
for(graphNode node: map.get(i).aList){
System.out.print(node.value+" ");
}
System.out.println("");
}
traverse(map);
}
public static void traverse(TreeMap map){
for(int i = 1; i <= map.size(); i++){
for(graphNode node: map.get(i).aList){
System.out.print(node.value+" ");
}
System.out.println("");
}
}
}
import java.util.*;
import java.io.*;
public class graphNode implements Comparable<graphNode> {
int value;
int distance;
graphNode prev;
TreeSet<graphNode> aList;
String color;
public graphNode(int value, graphNode prev, int distance) {
this.value = value;
this.prev = prev;
this.distance = distance;
aList = new TreeSet<graphNode>();
String color = "white";
}
public String toString() {
return value + "";
}
public int compareTo(graphNode other) {
if (this.value < other.value){
return -1;
}else if (this.value == other.value){
return 0;
}else{
return 1;
}
}
}