Skip to content

Instantly share code, notes, and snippets.

@rohithpeddi
Last active November 13, 2016 08:02
Show Gist options
  • Save rohithpeddi/24b24c23b161c99487fabdd544b02d93 to your computer and use it in GitHub Desktop.
Save rohithpeddi/24b24c23b161c99487fabdd544b02d93 to your computer and use it in GitHub Desktop.
BFS of EdgeWeightedGraph
static class BFS {
boolean[] marked;
int[] distTo;
public BFS(EdgeWeightedGraph G, int source) {
marked = new boolean[G.noOfVertices];
distTo = new int[G.noOfVertices];
for(int i=0; i<G.noOfVertices; i++ ){
distTo[i] = Integer.MAX_VALUE ;
}
bfs(G, source);
}
public void bfs(EdgeWeightedGraph G, int s) {
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(s);
marked[s] = true;
distTo[s] = 0;
while (!queue.isEmpty()) {
int v = queue.remove();
for (Edge e : G.getAdjEdges(v)) {
int w = e.otherVertex(v);
if (!marked[w]) {
queue.add(w);
marked[w] = true;
distTo[w] = distTo[v] + e.getWeight() ;
}
}
}
}
public boolean hasPathTo(int v) {
return marked[v];
}
public int distTo(int v) {
return distTo[v];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment