import java.util.*; public class Graph { enum Status { UNEXPLORED, EXPLORED, EXPLORING } HashMap, List>> graph; public Graph() { graph = new HashMap, List>>(); } /** * restituisce i nodi del grafo * */ public Collection> getNodes() { return graph.keySet(); } /** * restituisce la lista di adiacenza di un nodo * */ public Collection> getOutEdges(Node source) { return graph.get(source); } /** * aggiunge un nuovo arco al grafo * */ public void insertEdge(Node source, Node destination) throws Exception { if (! (graph.containsKey(source) && graph.containsKey(destination)) ) throw new Exception("Nodo non presente nel grafo"); graph.get(source).add(destination); } /** * aggiunge un nuovo nodo al grafo * */ public void insertNode(Node v) { if (! graph.containsKey(v)) graph.put(v, new LinkedList>()); } /** * esegue una dfs * */ public void dfs() { HashMap, Status> status = new HashMap, Status>(); HashMap, Integer> timest = new HashMap, Integer>(); for (Node u : getNodes()) { status.put(u, Status.UNEXPLORED); timest.put(u, 0); } int loctime = 0; for (Node v : getNodes()) { System.out.println("Root "+v); loctime += sweep(v, status, timest, loctime); } } private int sweep(Node source, HashMap, Status> status, HashMap, Integer> timest, int time) { if (status.get(source) != Status.UNEXPLORED) return 0; int loctime = 1; status.put(source, Status.EXPLORING); timest.put(source, time); for (Node u : getOutEdges(source)) { System.out.print(source+"("+timest.get(source)+")->"+u+"("+timest.get(u)+") "); if(status.get(u) == Status.EXPLORED) { if (timest.get(source) < timest.get(u)) System.out.println("FORW"); else System.out.println("CROS"); continue; } if(status.get(u) == Status.EXPLORING) { System.out.println("BACK"); continue; } System.out.println("TREE"); loctime += sweep(u, status, timest, time+loctime); } status.put(source, Status.EXPLORED); return loctime; } }