|
| 1 | +package com.github.chen0040.leetcode.day18.medium; |
| 2 | + |
| 3 | + |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | + |
| 7 | +/** |
| 8 | + * Created by xschen on 13/8/2017. |
| 9 | + * |
| 10 | + * link: https://leetcode.com/problems/word-ladder/description/ |
| 11 | + */ |
| 12 | +public class WordLadder { |
| 13 | + |
| 14 | + static class Graph { |
| 15 | + Map<String, List<String>> adjList = new HashMap<String, List<String>>(); |
| 16 | + public void addEdge(String v, String w) { |
| 17 | + adj(v).add(w); |
| 18 | + adj(w).add(v); |
| 19 | + } |
| 20 | + |
| 21 | + public List<String> adj(String v){ |
| 22 | + if(adjList.containsKey(v)){ |
| 23 | + return adjList.get(v); |
| 24 | + } else { |
| 25 | + List<String> list = new ArrayList<String>(); |
| 26 | + adjList.put(v, list); |
| 27 | + return list; |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + public int search(String s, String t) { |
| 32 | + Set<String> marked = new HashSet<String>(); |
| 33 | + Map<String, Integer> costs = new HashMap<String, Integer>(); |
| 34 | + Queue<String> queue = new LinkedList<String>(); |
| 35 | + queue.add(s); |
| 36 | + costs.put(s, 0); |
| 37 | + while(!queue.isEmpty()) { |
| 38 | + String v= queue.remove(); |
| 39 | + //System.out.println(v); |
| 40 | + List<String> adj_v = adj(v); |
| 41 | + marked.add(v); |
| 42 | + if(v.equals(t)) break; |
| 43 | + for(String w : adj_v){ |
| 44 | + if(costs.getOrDefault(w, Integer.MAX_VALUE / 2) > costs.get(v) + 1) { |
| 45 | + costs.put(w, costs.get(v) + 1); |
| 46 | + if(!marked.contains(w)) { |
| 47 | + queue.add(w); |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + if(costs.containsKey(t)) { |
| 54 | + return costs.get(t) + 1; |
| 55 | + } else { |
| 56 | + return 0; |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + public class Solution { |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | + public int ladderLength(String beginWord, String endWord, List<String> wordList) { |
| 66 | + Graph g = new Graph(); |
| 67 | + wordList.add(beginWord); |
| 68 | + for(int i=0; i < wordList.size(); ++i) { |
| 69 | + String w1 = wordList.get(i); |
| 70 | + for(int j=i+1; j < wordList.size(); ++j) { |
| 71 | + String w2 = wordList.get(j); |
| 72 | + if(isConnected(w1, w2)) { |
| 73 | + g.addEdge(w1, w2); |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + return g.search(beginWord, endWord); |
| 79 | + } |
| 80 | + |
| 81 | + private boolean isConnected(String w1, String w2) { |
| 82 | + if(w1.length() != w2.length()) return false; |
| 83 | + int count = 0; |
| 84 | + for(int i=0; i < w1.length(); ++i) { |
| 85 | + if(w1.charAt(i) != w2.charAt(i)) { |
| 86 | + count++; |
| 87 | + } |
| 88 | + } |
| 89 | + return count==1; |
| 90 | + } |
| 91 | + } |
| 92 | +} |
0 commit comments