Skip to content

Instantly share code, notes, and snippets.

@techisbeautiful
Created July 12, 2022 08:03
Show Gist options
  • Save techisbeautiful/0399856b23030e30eca92f56a8f6a03a to your computer and use it in GitHub Desktop.
Save techisbeautiful/0399856b23030e30eca92f56a8f6a03a to your computer and use it in GitHub Desktop.
class MyGraph {
private int vertices;
private LinkedList<Integer> adjacency[];
MyGraph(int v) {
vertices = v;
adjacency = new LinkedList[v];
for (int i = 0; i < v; ++i)
adjacency[i] = new LinkedList();
}
// Add an edge into the graph
void addEdge(int v, int w) {
adjacency[v].add(w);
}
// A function used by DFS
void dfsHelper(int v, boolean visited[]) {
// Mark the current node as visited and print it
visited[v] = true;
System.out.print(v + " ");
// Recurse for all the vertices adjacent to this vertex
Iterator<Integer> i = adjacency[v].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n])
dfsHelper(n, visited);
}
}
void traverseBFS(int v) {
// Set all the vertices as not visited, set as false by default
boolean visited[] = new boolean[vertices];
// Print DFS traversal
dfsHelper(v, visited);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment