This repository acts as a personal archive for my solutions to EdX course *Data Structures and Software Design* from PennX.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

52 lines
1.2 KiB

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
/*
* SD2x Homework #6
* This is an implementation of Breadth First Search (BFS) on a graph.
* You may modify and submit this code if you'd like.
*/
public class BreadthFirstSearch {
protected Set<Node> marked;
protected Graph graph;
public BreadthFirstSearch(Graph graphToSearch) {
marked = new HashSet<Node>();
graph = graphToSearch;
}
/**
* This method was discussed in the lesson
*/
public boolean bfs(Node start, String elementToFind) {
if (!graph.containsNode(start)) {
return false;
}
if (start.getElement().equals(elementToFind)) {
return true;
}
Queue<Node> toExplore = new LinkedList<Node>();
marked.add(start);
toExplore.add(start);
while (!toExplore.isEmpty()) {
Node current = toExplore.remove();
for (Node neighbor : graph.getNodeNeighbors(current)) {
if (!marked.contains(neighbor)) {
if (neighbor.getElement().equals(elementToFind)) {
return true;
}
marked.add(neighbor);
toExplore.add(neighbor);
}
}
}
return false;
}
}