Skip to content

Latest commit

 

History

History
 
 

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 

学习笔记 双向BFS模板

    // 双向BFS用set而不用队列
    Set<String> beginSet = new HashSet<>(), endSet = new HashSet<>();
    Set<String> visited = new HashSet<>();
    int count = 1;
    beginSet.add(beginWord);
    endSet.add(endWord);

    while (!beginSet.isEmpty() && !endSet.isEmpty()) {
      // 优化,每次选最短的进行处理
      if (beginSet.size() > endSet.size()) {
        swapSet(beginSet, endSet);
      }

      // 哈希集合在遍历的过程中不能修改,用 temp 存储扩散结果
      Set<String> temp = new HashSet<>();

      // 从beginSet中的所有结点开始扩散
      for (String word : beginSet) {
        List<String> variants = generateWordVariant(word, wordSet);
        for (String target : variants) {
          // 已经找到,直接返回
          if (endSet.contains(target)) {
            return count + 1;
          }
          // 注意:加入set的时候就更新visited,避免同一结点多次添加set
          if (!visited.contains(target) && wordSet.contains(target)) {
            temp.add(target);
            visited.add(target);
          }
        }
      }
      // 注意:将temp扩散后结果放入新的beginset
      beginSet = temp;
      // 增加步数
      count++;
    }