zoukankan      html  css  js  c++  java
  • 单词最短路径

    Input:
    beginWord = "hit",
    endWord = "cog",
    wordList = ["hot","dot","dog","lot","log","cog"]
    
    Output: 5
    
    Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
    return its length 5.

    public int ladderLength(String beginWord,String endWord,List<String> wordList){
            wordList.add(beginWord);
            int start = wordList.size()-1;
            int end = 0;
            while(end<wordList.size()&& !wordList.get(end).equals(end)){
                end++;
            }
            if (end == wordList.size()){
                return 0;
            }
            List<Integer>[] graphic = buildGraphic(wordList);
            return getShortestPath(graphic,start,end);
        }
        
        private List<Integer>[] buildGraphic(List<String> wordList){
            int N = wordList.size();
            List<Integer>[] graphic = new List[N];
            for(int i=0;i<N;i++){
                graphic[i] = new ArrayList<Integer>();
                for(int j=0;j<N;j++){
                    if(isConnect(wordList.get(i),wordList.get(j))){
                        graphic[i].add(j);
                    }
                }
            }
            return graphic;
            
        }
        
        private boolean isConnect(String s1,String s2){
            int diffCnt = 0;
            for(int i=0;i<s1.length()&&diffCnt<=1;i++){
                if(s1.charAt(i)!=s2.charAt(i)){
                    diffCnt++;
                }
            }
            return diffCnt == 1;
        }
        
        
        private int getShortestPath(List<Integer>[] graphic,int start,int end){
            Queue<Integer> queue = new LinkedList<Integer>();
            boolean[] marked = new boolean[graphic.length];
            queue.add(start);
            marked[start] = true;
            int path = 1;
            while(!queue.isEmpty()){
                int size = queue.size();
                path++;
                while(size-->0){
                    int cur = queue.poll();
                    for(int next:graphic[cur]){
                        if(next == end){
                            return path;
                        }
                        if(marked[next]){
                            continue;
                        }
                        marked[next] = true;
                        queue.add(next);
                    }
                }
            }
            return 0;
        }
        
  • 相关阅读:
    数组的typedef 和函数的typedef
    函数返回值当左值的问题
    C++中虚析构函数的作用
    word2013密钥
    子类父类步长问题
    函数重定义——重写———重载
    C++的成员初始化列表和构造函数体(以前未知)
    常引用
    项目开发中的字符串模型
    指针函数的++(极易犯错误)
  • 原文地址:https://www.cnblogs.com/helloworldmybokeyuan/p/13446213.html
Copyright © 2011-2022 走看看