From f80dce4991c29c9ab963c474ec7638eb096cb0eb Mon Sep 17 00:00:00 2001
From: Luigi Santocanale <luigi.santocanale@lif.univ-mrs.fr>
Date: Fri, 6 Dec 2019 08:38:36 +0100
Subject: [PATCH] Added BreadthFirstSearch.java

---
 src/BreadthFirstSearch.java | 46 +++++++++++++++++++++++++++++++++++++
 1 file changed, 46 insertions(+)
 create mode 100644 src/BreadthFirstSearch.java

diff --git a/src/BreadthFirstSearch.java b/src/BreadthFirstSearch.java
new file mode 100644
index 0000000..f370f25
--- /dev/null
+++ b/src/BreadthFirstSearch.java
@@ -0,0 +1,46 @@
+import java.util.ArrayList;
+import java.util.BitSet;
+import java.util.LinkedList;
+import java.util.Queue;
+
+
+public class BreadthFirstSearch {
+
+	Graph graph;
+	Queue<Arc> frontier;
+	ArrayList<Arc> tree;
+	BitSet reached;
+	
+	private void push(int vertex) {
+		for (Arc arc : graph.outNeighbours(vertex)) frontier.offer(arc);
+	}
+	
+	private void explore(Arc nextArc) {
+		if (reached.get(nextArc.getDest())) return;
+		reached.set(nextArc.getDest());
+		tree.add(nextArc);
+		push(nextArc.getDest());
+	}
+
+	private void bfs(int startingVertex) {
+		reached.set(startingVertex);
+		push(startingVertex);
+		while (!frontier.isEmpty()) {
+			explore(frontier.poll());
+		}
+	}
+	
+	private BreadthFirstSearch (Graph graph) {
+		this.graph = graph;
+		this.frontier = new LinkedList<>();
+		this.tree = new ArrayList<>();
+		this.reached = new BitSet(graph.order);
+	}
+	
+	public static ArrayList<Arc> generateTree(Graph graph, int root) {
+		BreadthFirstSearch algo = new BreadthFirstSearch(graph);
+		algo.bfs(root);
+		return algo.tree;
+	}
+	
+}
-- 
GitLab