zoukankan      html  css  js  c++  java
  • 127. Word Ladder via java

    A classic BFS problem, that is, we use a Queue to store temporary solution and record the size of the current Queue. 

    For each node in this BFS tree, we try k times of transformation, k is the length of the word.

    We record every word which already has been seen in case of a loop. Thus we need a HashSet.

    public class Solution {
      // use BFS to solve
      // in every level of BFS searching, 
      // we find the word that replaced by one char and also in the dict without have seen before
      // data structure: seen(HashSet), cur(Queue)
      // assume that the wordList is not null, case insensitive, no duplicate, every word is non-empty
      public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        // Write your solution here
        HashSet<String> seen = new HashSet<>();
        Queue<String> cur = new LinkedList<>();
        seen.add(beginWord);
        cur.offer(beginWord);
        int cnt = 1;
        while(cur.size()>0){
          cnt++;
          int size = cur.size();
          for(int i=0; i<size; i++){
            String todo = cur.poll();
            for(int j=0; j<todo.length(); j++){
              List<String> changed= getQualified(todo, j, wordList, seen);
              for(String s: changed){
                if(String.valueOf(s)==String.valueOf(endWord)){
                  return cnt;
                }else{
                  cur.offer(s);
                  seen.add(s);
                }
              }
            }
          }
        }
        return 0;
      }
    
      private List<String> getQualified(String from, int ignore, List<String> wordList, HashSet<String> seen){
        List<String> res = new ArrayList<>();
        for(String s: wordList){
          int flag = 0;
          for(int i=0; i<from.length(); i++){
            if(i!=ignore && from.charAt(i)!=s.charAt(i)){
              flag=1;
            }
          }
          if(flag==0 && !seen.contains(s)){
            res.add(s);
          }
        }
        return res;
      }
    }
  • 相关阅读:
    使用kerl安装erlang遇到的问题及解决办法-bak
    zip无法解压
    利用正则表达式统计访问频率
    windows开dump
    ftp禁止切换回上级目录
    windows组策略屏蔽
    对于超体的一点思考
    测试php语句执行时间
    php中点击下载按钮后待下载文件被清空
    mysql_fetch_assoc查询多行数据
  • 原文地址:https://www.cnblogs.com/zg1005/p/11980615.html
Copyright © 2011-2022 走看看