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

[LeetCode]126 Word Ladder II

时间:2015-01-07 19:05:33      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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

http://blog.csdn.net/linhuanmars/article/details/23071455

public class Solution {
    public List<List<String>> findLadders(String start, String end, Set<String> dict)
    {
        List<List<String>> toReturn = new ArrayList<>();
        
        Queue<Node> queue = new LinkedList<>();
        queue.offer(new Node(start, new ArrayList<String>()));
        
        int minlen = -1;
        
        Set<String> visited = new HashSet<>();
        visited.add(start);
        
        while (!queue.isEmpty())
        {
            Node node = queue.poll();
            if (node.str.equals(end))
            {
                if (minlen == -1)
                {
                    toReturn.add(node.path);
                    minlen = node.path.size();
                }
                else if (node.path.size() == minlen)
                {
                    toReturn.add(node.path);
                }
            }
            else
            {
                visited.add(node.str);
                List<Node> nextnodes = next(node, dict, visited);
                for (Node nextnode : nextnodes)
                    queue.offer(nextnode);
            }
        }
        
        return toReturn;
    }
    
    
    private List<Node> next(Node from, Set<String> dict, Set<String> visited)
    {
        List<Node> toReturn = new ArrayList<>();
        
        char[] chars = from.str.toCharArray();
        for (int i = 0 ; i < chars.length ; i ++)
        {
            char oric = chars[i];
            for (char c = ‘a‘ ; c <= ‘z‘ ; c ++)
            {
                if (c == oric)
                    continue;
                chars[i] = c;
                String str = new String(chars);
                if (dict.contains(str) && !visited.contains(str))
                {
                    toReturn.add(new Node(str, from.path));
                }
            }
            chars[i] = oric;
        }
        
        return toReturn;
    }
    
    private static class Node
    {
        String str;
        List<String> path;
        Node(String str, List<String> oldpath)
        {
            this.str = str;
            path = new ArrayList<>(oldpath);
            path.add(str);
        }
    }
}


[LeetCode]126 Word Ladder II

标签:leetcode

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

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