Skip to content

Instantly share code, notes, and snippets.

@pori
Last active August 29, 2015 14:05
Show Gist options
  • Save pori/79735dde4aff32c81ca0 to your computer and use it in GitHub Desktop.
Save pori/79735dde4aff32c81ca0 to your computer and use it in GitHub Desktop.
An overly simple breadth first search implementation.
import java.util.Queue;
import java.util.List;
import java.util.LinkedList;
import java.util.ArrayList;
public class BreadthFirstSearch {
public static void main(String args[]) {
int[][] graph = {
{ 0, 1, 2 },
{ 0, 1, 2 },
{ 0, 1, 2 },
};
int target = BreadthFirstSearch.BFS(graph, 0, 2);
System.out.println(Integer.toString(target));
}
public static int BFS(int[][] G, int v, int target) {
Queue<Integer> Q = new LinkedList<Integer>();
List<Integer> V = new ArrayList<Integer>();
V.add(v);
Q.add(v);
while (!Q.isEmpty()) {
int t = (int) Q.remove();
if (t == target) {
return t;
}
for (int e: G[t]) {
if (!V.contains(e)) {
V.add(e);
Q.add(e);
}
}
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment