Skip to content

Instantly share code, notes, and snippets.

@Xrayez
Forked from deyindra/BreadthFirstIterator
Created February 8, 2022 13:35
Show Gist options
  • Save Xrayez/e67858723beca83f972f5790aae3a26f to your computer and use it in GitHub Desktop.
Save Xrayez/e67858723beca83f972f5790aae3a26f to your computer and use it in GitHub Desktop.
BFS and DFS Iterator for Graph
import java.util.*;
public class BreadthFirstIterator<T> implements Iterator<T> {
private Set<T> visited = new HashSet<>();
private Queue<T> queue = new LinkedList<>();
private Graph<T> graph;
public BreadthFirstIterator(Graph<T> g, T startingVertex) {
if(g.isVertexExist(startingVertex)) {
this.graph = g;
this.queue.add(startingVertex);
this.visited.add(startingVertex);
}else{
throw new IllegalArgumentException("Vertext does not exits");
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public boolean hasNext() {
return !this.queue.isEmpty();
}
@Override
public T next() {
if(!hasNext())
throw new NoSuchElementException();
//removes from front of queue
T next = queue.remove();
for (T neighbor : this.graph.getNeighbors(next)) {
if (!this.visited.contains(neighbor)) {
this.queue.add(neighbor);
this.visited.add(neighbor);
}
}
return next;
}
public static void main(String[] args) {
Graph<Integer> graph = new Graph<>();
graph.addEdge(1,2);
graph.addEdge(1,3);
graph.addEdge(2,4);
graph.addEdge(4,1);
graph.addEdge(5,null);
BreadthFirstIterator<Integer> bfs = new BreadthFirstIterator<>(graph,5);
while (bfs.hasNext()){
System.out.println(bfs.next());
}
}
}
import java.util.*;
public class DepthFirstSearchIterator<T> implements Iterator<T> {
private Set<T> visited = new HashSet<>();
private Stack<Iterator<T>> stack = new Stack<>();
private Graph<T> graph;
private T next;
public DepthFirstSearchIterator(Graph g, T startingVertex) {
if(g.isVertexExist(startingVertex)) {
this.stack.push(g.getNeighbors(startingVertex).iterator());
this.graph = g;
this.next = startingVertex;
}else{
throw new IllegalArgumentException("Vertext does not exits");
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public boolean hasNext() {
return this.next != null;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
try {
this.visited.add(this.next);
return this.next;
} finally {
this.advance();
}
}
private void advance() {
Iterator<T> neighbors = this.stack.peek();
do {
while (!neighbors.hasNext()) { // No more nodes -> back out a level
this.stack.pop();
if (this.stack.isEmpty()) { // All done!
this.next = null;
return;
}
neighbors = this.stack.peek();
}
this.next = neighbors.next();
} while (this.visited.contains(this.next));
this.stack.push(this.graph.getNeighbors(this.next).iterator());
}
public static void main(String[] args) {
Graph<Integer> graph = new Graph<>();
graph.addEdge(1,2);
graph.addEdge(1,3);
graph.addEdge(2,4);
graph.addEdge(4,1);
graph.addEdge(5,null);
DepthFirstSearchIterator<Integer> dfs = new DepthFirstSearchIterator<>(graph,1);
while (dfs.hasNext()){
System.out.println(dfs.next());
}
}
}
import java.util.*;
public class Graph<T> {
private Map<T, Set<T>> map;
public Graph() {
map = new HashMap<>();
}
public Graph addEdge(T src, T destination){
if(src!=null){
if(src==destination || src.equals(destination)){
throw new IllegalArgumentException("Source and Destination can not be same");
}else{
Set<T> desitinations = map.get(src);
if(desitinations==null){
desitinations = new HashSet<>();
}
if(destination!=null){
desitinations.add(destination);
Set<T> destinationsOfDestination = map.get(destination);
if(destinationsOfDestination==null){
map.put(destination, new HashSet<T>());
}
}
map.put(src,desitinations);
}
}else{
throw new IllegalArgumentException("Invalid Source node");
}
return this;
}
public Iterable<T> getNeighbors(T vertex) {
Set<T> neighbors = this.map.get(vertex);
if (neighbors == null || neighbors.isEmpty()) {
return Collections.emptySet();
} else {
return Collections.unmodifiableSet(neighbors);
}
}
public boolean isVertexExist(T vertex){
return map.containsKey(vertex);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Graph{");
sb.append("map=").append(map);
sb.append('}');
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment