Created
November 25, 2016 06:22
-
-
Save zacharycarter/5c2d30d78d2906de6549a4ae28ac4c1d to your computer and use it in GitHub Desktop.
This file contains 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
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