Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package aiz7;
- /**
- *
- * @author MaxSylverWolf
- */
- import java.util.*;
- class Tarjan
- {
- //wierzcholki
- private int V;
- private int preCount;
- private int[] low;
- //odwiedzanie
- private boolean[] visited;
- //lista utworzonego grafu
- private List<Integer>[] graph;
- //wszystkie silnie/elementy maksymalne(najwięcej połączeń)
- private List<List<Integer>> sccComp;
- private Stack<Integer> stack;
- //Silnia składowa grafu
- public List<List<Integer>> getSCComponents(List<Integer>[] graph)
- {
- V = graph.length;
- this.graph = graph;
- low = new int[V];
- visited = new boolean[V];
- stack = new Stack<Integer>();
- sccComp = new ArrayList<>();
- for (int v = 0; v < V; v++)
- if (!visited[v])
- dfs(v);
- return sccComp;
- }
- //Algorytm DFS, przeszukiwanie w głąb
- public void dfs(int v)
- {
- low[v] = preCount++;
- visited[v] = true;
- stack.push(v);
- int min = low[v];
- for (int w : graph[v])
- {
- if (!visited[w])
- dfs(w);
- if (low[w] < min)
- min = low[w];
- }
- if (min < low[v])
- {
- low[v] = min;
- return;
- }
- List<Integer> component = new ArrayList<Integer>();
- int w;
- do
- {
- w = stack.pop();
- component.add(w);
- low[w] = V;
- } while (w != v);
- sccComp.add(component);
- }
- public static void main(String[] args)
- {
- Scanner scan = new Scanner(System.in);
- System.out.println("SCC test:\n");
- System.out.println("Liczba wierzchołków: ");
- int V = scan.nextInt();
- //tworze graf
- List<Integer>[] g = new List[V];
- for (int i = 0; i < V; i++)
- g[i] = new ArrayList<Integer>();
- // krawędzie
- System.out.println("\nLiczba krawędzi");
- int E = scan.nextInt();
- //krawędzie
- System.out.println("Podaj "+ E +" x, y elementy: ");
- for (int i = 0; i < E; i++)
- {
- int x = scan.nextInt();
- int y = scan.nextInt();
- g[x].add(y);
- }
- System.out.println("Graf:");
- for (int i = 0; i < V; i++)
- System.out.println(i+"|"+g[i]);
- Tarjan t = new Tarjan();
- System.out.println("SCC : ");
- //WSZYSTKIE SCC / czyli te silnie
- List<List<Integer>> scComponents = t.getSCComponents(g);
- System.out.println(scComponents);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement