Last active
August 29, 2015 14:05
-
-
Save pori/79735dde4aff32c81ca0 to your computer and use it in GitHub Desktop.
An overly simple breadth first search implementation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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