简体   繁体   中英

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. 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. Any suggestions/guidelines.

Re-implement this in an OOP-with-GC way - each node should have a set of nodes it has edges to. Then this problem becomes quite easy. You iterate the adjacent nodes of the start node. For DFS, you recurse on each node. For BFS, you put the nodes in a Deque, and always get the Deque's tail.

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. make sure you use SEED= Integer.max_value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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