简体   繁体   English

Java 中无向无权图上的 BFS 和 DFS

[英]BFS and DFS on a undirected and unweighed Graph in Java

public class Graph {
 private int V; //Number of vertices
    private int E; // Number of edges
    private ArrayList<Integer>[] adj; 

 public void addEdge(int v, int w) {
        if (!this.adj[v].contains(w)) {
            this.adj[v].add(w);
        }

        if (!this.adj[w].contains(v)) {
            this.adj[w].add(v);
        }
    }
public Graph bfs(int s) {

    }
public Graph dfs(int s) {

    }

I have created Graph in java such that an array of ArrayList holds the vertices attached to another vertices.我在 java 中创建了 Graph,这样一个 ArrayList 数组包含附加到另一个顶点的顶点。 I want to Implement BFS and DFS on this structure of Graph such that that I get a DFS/BFS graph from a single source.我想在这个 Graph 结构上实现 BFS 和 DFS,这样我就可以从单一来源获得 DFS/BFS 图。 Any suggestions/guidelines.任何建议/指南。

Re-implement this in an OOP-with-GC way - each node should have a set of nodes it has edges to.以 OOP-with-GC 方式重新实现它 - 每个节点都应该有一组它有边的节点。 Then this problem becomes quite easy.那么这个问题就变得很容易了。 You iterate the adjacent nodes of the start node.您迭代起始节点的相邻节点。 For DFS, you recurse on each node.对于 DFS,您在每个节点上递归。 For BFS, you put the nodes in a Deque, and always get the Deque's tail.对于 BFS,你将节点放在一个 Deque 中,并且总是得到 Deque 的尾部。

Just use the red-black tree to get in-order traversal of graph, once you get traversal use Math.random() to replace all existing values with new ones.只需使用红黑树来获得图的有序遍历,一旦获得遍历,请使用 Math.random() 将所有现有值替换为新值。 make sure you use SEED= Integer.max_value;确保您使用 SEED= Integer.max_value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM