Created
July 12, 2022 08:03
-
-
Save techisbeautiful/0399856b23030e30eca92f56a8f6a03a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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