Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int bfsCount(Map<String, List<String>> graph, String startingValue,
- String endingValue) {
- Map<String, Boolean> seenMap = new HashMap<String, Boolean>();
- Iterator<String> keysI = graph.keySet().iterator();
- // initialize a map indicating whether a word has been visited, ie
- // part of the transformation sequence
- while(keysI.hasNext()) {
- String key = keysI.next();
- seenMap.put(key, false);
- }
- // queue to manager this BFS
- Queue<String> q = new LinkedList<String>();
- // enqueue
- q.offer(startingValue);
- seenMap.put(startingValue, true);
- System.out.println(startingValue);
- // similar to tree BFS but we only add unseen children(edges) to the queue
- int count = 1;
- while(!q.isEmpty()) {
- // dequeue
- String head = q.poll();
- List<String> neighbors = graph.get(head);
- for (String neighbor: neighbors) {
- boolean visitedVertex = seenMap.get(neighbor);
- if (!visitedVertex) {
- count++;
- q.offer(neighbor);
- seenMap.put(neighbor, true);
- System.out.println(neighbor);
- if (neighbor.equals(endingValue)) {
- return count;
- }
- }
- }
- }
- return count;
- }
Add Comment
Please, Sign In to add comment