Java中的深度优先搜索-无法将节点转换为int

问题描述 投票:0回答:1

我需要执行深度优先搜索,但是当我尝试实现此代码时,出现错误“无法将节点转换为int。”我知道类型不匹配,但是我不确定如何更正它才能正常工作。下面是我的方法代码:

public void DFS(){
    int node = g.node;
    System.out.print("Depth First Traversal: ");
    boolean[] visited = new boolean[node];
    Stack<Integer> stack = new Stack<Integer>();

    for(int startIndex=0; startIndex<node; startIndex++){
        if(visited[startIndex]==false) {
            stack.push(startIndex);
            visited[startIndex] = true;
            while (stack.isEmpty() == false) {
                int nodeIndex = stack.pop();
                System.out.print(nodeIndex + " ");
                ArrayList<Node> nodeList = g.nodeList;
                for (int i = 0; i < nodeList.size(); i++) {
                    int dest = nodeList.get(i);
                    if (visited[dest] == false) {
                        stack.push(dest);
                        visited[dest] = true;
                    }
                }
            }
        }
    }
    System.out.println();
}

这是我正在使用的我的图类。

public class Graph {

    ArrayList<Node> nodeList;
    ArrayList<Edge> edgeList;
    public boolean visited[];
    int node;

    public Graph() {
        nodeList = new ArrayList<Node>();
        edgeList = new ArrayList<Edge>();
    }

    public ArrayList<Node> getNodeList() {
        return nodeList;
    }

    public ArrayList<Edge> getEdgeList() {
        return edgeList;
    }

    public void addNode(Node n) {
        nodeList.add(n);
    }

    public void addEdge(Edge e) {
        edgeList.add(e);
    }
java depth-first-search
1个回答
0
投票

你有这个]

ArrayList<Node> nodeList = g.nodeList;
// ...
int dest = nodeList.get(i);

很可能nodeList是Nodes的列表,因此无法将其中的Node之一保存到数字dest中。如果要在Node内输入一些数字,则必须编写类似int dest = nodeList.get(i).getIndex()的数字(仅作为示例,名称取决于Node的属性)

© www.soinside.com 2019 - 2024. All rights reserved.