modify graph implementation

This commit is contained in:
DOHA 2019-07-28 00:01:06 +03:00
parent 5b5733239c
commit 24135c03cf
2 changed files with 24 additions and 17 deletions

View File

@ -1,36 +1,36 @@
package com.baeldung.graph;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
public class Graph {
private List<List<Integer>> neighbours;
private int n;
private Map<Integer, List<Integer>> adjVertices;
public Graph(int n) {
this.n = n;
this.neighbours = new ArrayList<List<Integer>>(n);
for (int i = 0; i < n; i++) {
this.neighbours.add(new ArrayList<Integer>());
}
public Graph() {
this.adjVertices = new HashMap<Integer, List<Integer>>();
}
public void addVertex(int vertex) {
adjVertices.putIfAbsent(vertex, new ArrayList<>());
}
public void addEdge(int src, int dest) {
this.neighbours.get(src)
.add(dest);
adjVertices.get(src).add(dest);
}
public void dfsWithoutRecursion(int start) {
Stack<Integer> stack = new Stack<Integer>();
boolean[] isVisited = new boolean[n];
boolean[] isVisited = new boolean[adjVertices.size()];
stack.push(start);
while (!stack.isEmpty()) {
int current = stack.pop();
isVisited[current] = true;
System.out.print(" " + current);
for (int dest : neighbours.get(current)) {
for (int dest : adjVertices.get(current)) {
if (!isVisited[dest])
stack.push(dest);
}
@ -38,14 +38,14 @@ public class Graph {
}
public void dfs(int start) {
boolean[] isVisited = new boolean[n];
boolean[] isVisited = new boolean[adjVertices.size()];
dfsRecursive(start, isVisited);
}
private void dfsRecursive(int current, boolean[] isVisited) {
isVisited[current] = true;
System.out.print(" " + current);
for (int dest : neighbours.get(current)) {
for (int dest : adjVertices.get(current)) {
if (!isVisited[dest])
dfsRecursive(dest, isVisited);
}
@ -53,7 +53,7 @@ public class Graph {
public void topologicalSort(int start) {
Stack<Integer> result = new Stack<Integer>();
boolean[] isVisited = new boolean[n];
boolean[] isVisited = new boolean[adjVertices.size()];
topologicalSortRecursive(start, isVisited, result);
while (!result.isEmpty()) {
System.out.print(" " + result.pop());
@ -62,10 +62,11 @@ public class Graph {
private void topologicalSortRecursive(int current, boolean[] isVisited, Stack<Integer> result) {
isVisited[current] = true;
for (int dest : neighbours.get(current)) {
for (int dest : adjVertices.get(current)) {
if (!isVisited[dest])
topologicalSortRecursive(dest, isVisited, result);
}
result.push(current);
}
}

View File

@ -19,7 +19,13 @@ public class GraphUnitTest {
}
private Graph createDirectedGraph() {
Graph graph = new Graph(6);
Graph graph = new Graph();
graph.addVertex(0);
graph.addVertex(1);
graph.addVertex(2);
graph.addVertex(3);
graph.addVertex(4);
graph.addVertex(5);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);