码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]127 Word Ladder

时间:2015-01-07 19:08:18      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:leetcode

https://oj.leetcode.com/problems/word-ladder/

http://blog.csdn.net/linhuanmars/article/category/1918893/2

public class Solution {
    public int ladderLength(String start, String end, Set<String> dict)
    {
        // Put end into dict
        Set<String> dictionary = new HashSet<>(dict);
        dictionary.add(end);

        Set<String> visited = new HashSet<>();
        
        // BFS
        int nextlevel = 0;
        int curlevel = 1;
        int result = 1;
        
        Queue<String> queue = new LinkedList<>();
        queue.offer(start);
        visited.add(start);
        
        while (!queue.isEmpty())
        {
            String node = queue.poll();
            if (node.equals(end))
                return result;
                
            curlevel --;
                
            Set<String> nextstrs = findnext(node, dictionary, visited);
            for (String nextstr : nextstrs)
            {
                queue.offer(nextstr);
            }
            nextlevel += nextstrs.size();
            
            if (curlevel == 0)
            {
                // This level is finished
                curlevel = nextlevel;
                nextlevel = 0;
                result ++;
            }
        }
        
        return 0;
    }
    
    // Given string, find next str from dict (excluding visited)
    private Set<String> findnext(String from, Set<String> dict, Set<String> visited)
    {
        Set<String> toReturn = new HashSet<>();
        char[] chars = from.toCharArray();
        for (int i = 0 ; i < chars.length ; i ++)
        {
            char originalc = chars[i];
            for (char j = ‘a‘ ; j <= ‘z‘ ; j ++)
            {
                if (originalc == j)
                    continue;
                    
                chars[i] = j;
                String str = new String(chars);
                if (dict.contains(str) && !visited.contains(str))
                {
                    toReturn.add(str);
                    
                    // NOTE
                    // Pre put str into visited, because we will anyway visited
                    // This is to increase latency.
                    visited.add(str);
                }
            }
            
            // NOTE
            // Don‘t forget change it back.
            chars[i] = originalc;
        }
        return toReturn;
    }
}


[LeetCode]127 Word Ladder

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1600279

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!