Guest User

Untitled

a guest
Jul 22nd, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. int bfsCount(Map<String, List<String>> graph, String startingValue,
  2. String endingValue) {
  3. Map<String, Boolean> seenMap = new HashMap<String, Boolean>();
  4. Iterator<String> keysI = graph.keySet().iterator();
  5. // initialize a map indicating whether a word has been visited, ie
  6. // part of the transformation sequence
  7. while(keysI.hasNext()) {
  8. String key = keysI.next();
  9. seenMap.put(key, false);
  10. }
  11.  
  12. // queue to manager this BFS
  13. Queue<String> q = new LinkedList<String>();
  14. // enqueue
  15. q.offer(startingValue);
  16. seenMap.put(startingValue, true);
  17. System.out.println(startingValue);
  18.  
  19. // similar to tree BFS but we only add unseen children(edges) to the queue
  20. int count = 1;
  21. while(!q.isEmpty()) {
  22. // dequeue
  23. String head = q.poll();
  24. List<String> neighbors = graph.get(head);
  25.  
  26. for (String neighbor: neighbors) {
  27. boolean visitedVertex = seenMap.get(neighbor);
  28. if (!visitedVertex) {
  29. count++;
  30. q.offer(neighbor);
  31. seenMap.put(neighbor, true);
  32. System.out.println(neighbor);
  33.  
  34. if (neighbor.equals(endingValue)) {
  35. return count;
  36. }
  37. }
  38. }
  39. }
  40. return count;
  41. }
Add Comment
Please, Sign In to add comment