Skip to content

Added Newly graph algorithm #5682

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import java.util.List;
import java.util.Stack;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

public class stronglyConnectedComponent_Optimized {

public void btrack(HashMap<Integer, List<Integer>> adjList, int[] visited, Stack<Integer> dfsCallsNodes, int currentNode) {
visited[currentNode] = 1;
for (int i = 0; i < adjList.get(currentNode).size(); i++) {
int neighbor = adjList.get(currentNode).get(i);
if (visited[neighbor] == -1) {
btrack(adjList, visited, dfsCallsNodes, neighbor);
}
}
dfsCallsNodes.add(currentNode);
}

public void btrack2(HashMap<Integer, List<Integer>> adjRevList, int[] visited, int currentNode, List<Integer> newScc) {
visited[currentNode] = 1;
newScc.add(currentNode);
for (int i = 0; i < adjRevList.get(currentNode).size(); i++) {
int neighbor = adjRevList.get(currentNode).get(i);
if (visited[neighbor] == -1) {
btrack2(adjRevList, visited, neighbor, newScc);
}
}
}

public int getOutput(HashMap<Integer, List<Integer>> adjList, int N) {
int[] visited = new int[N];
Arrays.fill(visited, -1);
Stack<Integer> dfsCallsNodes = new Stack<>();


for (int i = 0; i < N; i++) {
if (visited[i] == -1) {
btrack(adjList, visited, dfsCallsNodes, i);
}
}




HashMap<Integer, List<Integer>> adjRevList = new HashMap<>();
for (int i = 0; i < N; i++) {
adjRevList.put(i, new ArrayList<>());
}

for (int i = 0; i < N; i++) {
for (int neighbor : adjList.get(i)) {
adjRevList.get(neighbor).add(i);
}
}


Arrays.fill(visited, -1);
int stronglyConnectedComponents = 0;
List<List<Integer>> sccs = new ArrayList<>();

while (!dfsCallsNodes.isEmpty()) {
int node = dfsCallsNodes.pop();
if (visited[node] == -1) {
List<Integer> newScc = new ArrayList<>();
btrack2(adjRevList, visited, node, newScc);
sccs.add(newScc);
stronglyConnectedComponents++;
}
}


return stronglyConnectedComponents;
}

}
Loading