Skip to content

Instantly share code, notes, and snippets.

@zacharycarter
Created November 25, 2016 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zacharycarter/5c2d30d78d2906de6549a4ae28ac4c1d to your computer and use it in GitHub Desktop.
Save zacharycarter/5c2d30d78d2906de6549a4ae28ac4c1d to your computer and use it in GitHub Desktop.
public void bfs(Node rootNode){
initializeNodes();
Queue q = new LinkedList();
q.add(rootNode);
rootNode.visited=true;
int parentDistance = 0;
int parentLevel = 0;
rootNode.setLevel(parentLevel);
rootNode.setDistance(parentDistance);
List<Node> nodeList = new ArrayList<Node>();
nodeList.add(rootNode);
nodesSortedByDistance.put(0, nodeList);
nodesSortedByLevel.put(0, nodeList);
nodesFound.add(rootNode);
while(!q.isEmpty()){
Node n = (Node)q.poll();
parentLevel = n.getLevel();
parentDistance = n.getDistance();
for(Edge edge : n.getNeighbors()){
Node adj = edge.getNeighbor(n);
if(!adj.visited){
int distance = parentDistance+edge.getWeight();
int level = parentLevel + 1;
adj.setLevel(level);
adj.setDistance(distance);
adj.visited=true;
q.add(adj);
nodesFound.add(adj);
if(nodesSortedByDistance.get(distance) == null) {
nodeList = new ArrayList<Node>();
nodeList.add(adj);
nodesSortedByDistance.put(distance, nodeList);
} else nodesSortedByDistance.get(distance).add(adj);
if(nodesSortedByLevel.get(level) == null) {
nodeList = new ArrayList<Node>();
nodeList.add(adj);
nodesSortedByLevel.put(level, nodeList);
} else nodesSortedByLevel.get(level).add(adj);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment