75 lines
2.1 KiB
Java
Raw Normal View History

2019-07-25 23:11:26 +03:00
package com.baeldung.graph;
import java.util.ArrayList;
2019-07-28 00:01:06 +03:00
import java.util.HashMap;
2019-08-02 14:35:52 +03:00
import java.util.LinkedList;
2019-07-25 23:11:26 +03:00
import java.util.List;
2019-07-28 00:01:06 +03:00
import java.util.Map;
2019-07-25 23:11:26 +03:00
import java.util.Stack;
public class Graph {
2019-07-28 00:01:06 +03:00
private Map<Integer, List<Integer>> adjVertices;
2019-07-25 23:11:26 +03:00
2019-07-28 00:01:06 +03:00
public Graph() {
this.adjVertices = new HashMap<Integer, List<Integer>>();
}
public void addVertex(int vertex) {
adjVertices.putIfAbsent(vertex, new ArrayList<>());
2019-07-25 23:11:26 +03:00
}
public void addEdge(int src, int dest) {
2019-07-28 00:01:06 +03:00
adjVertices.get(src).add(dest);
2019-07-25 23:11:26 +03:00
}
public void dfsWithoutRecursion(int start) {
Stack<Integer> stack = new Stack<Integer>();
2019-07-28 00:01:06 +03:00
boolean[] isVisited = new boolean[adjVertices.size()];
2019-07-25 23:11:26 +03:00
stack.push(start);
while (!stack.isEmpty()) {
int current = stack.pop();
isVisited[current] = true;
2019-08-02 14:35:52 +03:00
visit(current);
2019-07-28 00:01:06 +03:00
for (int dest : adjVertices.get(current)) {
2019-07-25 23:11:26 +03:00
if (!isVisited[dest])
stack.push(dest);
}
}
}
public void dfs(int start) {
2019-07-28 00:01:06 +03:00
boolean[] isVisited = new boolean[adjVertices.size()];
2019-07-25 23:11:26 +03:00
dfsRecursive(start, isVisited);
}
private void dfsRecursive(int current, boolean[] isVisited) {
isVisited[current] = true;
2019-08-02 14:35:52 +03:00
visit(current);
2019-07-28 00:01:06 +03:00
for (int dest : adjVertices.get(current)) {
2019-07-25 23:11:26 +03:00
if (!isVisited[dest])
dfsRecursive(dest, isVisited);
}
}
2019-08-02 14:35:52 +03:00
public List<Integer> topologicalSort(int start) {
LinkedList<Integer> result = new LinkedList<Integer>();
2019-07-28 00:01:06 +03:00
boolean[] isVisited = new boolean[adjVertices.size()];
2019-07-25 23:11:26 +03:00
topologicalSortRecursive(start, isVisited, result);
2019-08-02 14:35:52 +03:00
return result;
2019-07-25 23:11:26 +03:00
}
2019-08-02 14:35:52 +03:00
private void topologicalSortRecursive(int current, boolean[] isVisited, LinkedList<Integer> result) {
2019-07-25 23:11:26 +03:00
isVisited[current] = true;
2019-07-28 00:01:06 +03:00
for (int dest : adjVertices.get(current)) {
2019-07-25 23:11:26 +03:00
if (!isVisited[dest])
topologicalSortRecursive(dest, isVisited, result);
}
2019-08-02 14:35:52 +03:00
result.addFirst(current);
2019-07-25 23:11:26 +03:00
}
2019-07-28 00:01:06 +03:00
2019-08-02 14:35:52 +03:00
private void visit(int value) {
System.out.print(" " + value);
}
2019-07-25 23:11:26 +03:00
}