Skip to content
Snippets Groups Projects
Commit 268d39ba authored by kraleva's avatar kraleva
Browse files

make BFS iterative

parent 8a4b6435
No related branches found
No related tags found
1 merge request!29IterativeSCC
...@@ -63,6 +63,44 @@ public class ConnectedComponentGraph { ...@@ -63,6 +63,44 @@ public class ConnectedComponentGraph {
return list; return list;
} }
public ArrayList<Long> DFS(Long s, HashMap<Long, Boolean> visited) {
// Create a stack for DFS
Stack<Long> stack = new Stack<Long>();
ArrayList<Long> vertices = new ArrayList<Long>();
// Push the current source node
stack.push(s);
while (stack.empty() == false) {
// Pop a vertex from stack and print it
s = stack.peek();
stack.pop();
// Stack may contain same vertex twice. So
// we need to print the popped item only
// if it is not visited.
if (visited.get(s) == false) {
System.out.print(s + " ");
visited.put(s, true);
vertices.add(s);
}
// Get all adjacent vertices of the popped vertex s
// If a adjacent has not been visited, then push it
// to the stack.
Iterator<Long> itr = adj.get(s).iterator();
while (itr.hasNext()) {
Long v = itr.next();
if (!visited.get(v))
stack.push(v);
}
}
return vertices;
}
// Function that returns reverse (or transpose) of this ConnectedComponentGraph // Function that returns reverse (or transpose) of this ConnectedComponentGraph
public ConnectedComponentGraph getTranspose() { public ConnectedComponentGraph getTranspose() {
ConnectedComponentGraph g = new ConnectedComponentGraph(); ConnectedComponentGraph g = new ConnectedComponentGraph();
...@@ -130,7 +168,7 @@ public class ConnectedComponentGraph { ...@@ -130,7 +168,7 @@ public class ConnectedComponentGraph {
// Print Strongly connected component of the popped vertex // Print Strongly connected component of the popped vertex
if (visited.get(v) == false) { if (visited.get(v) == false) {
ArrayList<Long> component = gr.DFSUtil(v, visited); ArrayList<Long> component = gr.DFS(v, visited);
if (maxLength < component.size()) { if (maxLength < component.size()) {
maxLength = component.size(); maxLength = component.size();
largestComponent = component; largestComponent = component;
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment