如何在 Java 中的 DFS 图上搜索站点

问题描述

我希望能够通过用户输入来搜索该节点,然后显示所有相邻节点并显示它们之间的距离。我想知道是否可以帮助我理解为什么以及如何这样做。我有简单的基本代码,可以打印出 5 个节点的路径,就是这样。即使是指向正确方向的指针也会有所帮助。我了解 DFS 在纸面上的工作原理,但仅此而已。

这是应用程序

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Where would you like to start?");
        String start = scanner. nextLine();

        Vertex v1 = new Vertex("Castletown");
        Vertex v2 = new Vertex("Mountrath");
        Vertex v3 = new Vertex("Portlaois");
        Vertex v4 = new Vertex("Portarlington");
        Vertex v5 = new Vertex("Slieve Bloom");

        List<Vertex> list = new ArrayList<>();

        v1.addNeighbour(v2);
        v1.addNeighbour(v3);
        v3.addNeighbour(v4);
        v4.addNeighbour(v4);

        list.add(v1);
        list.add(v2);
        list.add(v3);
        list.add(v4);
        list.add(v5);

        Dfs dfs = new Dfs();
        dfs.dfs(list);
    }
}

这是顶点类

public class Vertex {
    private String name;
    private boolean visited;
    private List<Vertex> neighbour;

    public Vertex(String name) {
        this.name = name;
        this.neighbour = new ArrayList<>();
    }

    public void addNeighbour(Vertex vertex) {
        this.neighbour.add(vertex);

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isVisited() {
        return visited;
    }

    public void setVisited(boolean visited) {
        this.visited = visited;
    }

    public List<Vertex> getNeighbour() {
        return neighbour;
    }

    public void setNeighbour(List<Vertex> neighbour) {
        this.neighbour = neighbour;
    }

    public String toString() {
        return this.name;
    }
}

最后是 DFS 类

    private Stack<Vertex> stack;

public Dfs() {
    this.stack = new Stack<>();
}

public void dfs(List<Vertex> vertexList) {
    for(Vertex v:vertexList) {
        if(!v.isVisited()) {
            v.setVisited(true);
            dfsWithStack(v);
        }
    }
}

private void dfsWithStack(Vertex rootVertex) {
    this.stack.add(rootVertex);
    rootVertex.setVisited(true);
    while(!stack.isEmpty()) {
        Vertex actualVertex = this.stack.pop();
        System.out.println(actualVertex + " ");
        for(Vertex v: actualVertex.getNeighbour()) {
            if(!v.isVisited()) {
                v.setVisited(true);
                this.stack.push(v);
            }
        }
    }

}

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...