127. Word Ladder 单词梯子
https://leetcode.com/problems/word-ladder/
题目:给定两个单词(首词和尾词)和字典的单词列表,找出从开头到结尾的最短转换序列的长度,每次转换只能更改一个字母。每个转换后的单词必须存在于单词列表中。请注意,首词不是一个转换的词。
思路:BFS,
class Solution { public int ladderLength(String beginWord, String endWord, List<String> wordAsList) { if(beginWord.equals(endWord)) return 1; if (!wordAsList.contains(endWord)) { return 0; } Queue<String> queue = new LinkedList<>(); queue.add(beginWord); wordAsList.remove(beginWord); int level = 2; while(!queue.isEmpty()) { int size = queue.size(); for(int i = 0; i < size; i++) { String temp = queue.poll(); for(int j = 0; j < temp.length(); j++) { char[] chars = temp.toCharArray(); for(char c = 'a'; c <= 'z'; c++) { chars[j] = c; String strtemp = String.valueOf(chars); if(strtemp.equals(endWord)) return level; if(wordAsList.remove(strtemp)) { queue.add(strtemp); } } } } level++; } return 0; } }
图:
深搜/广搜:http://oj.leetcode.com/problems/clone-graph/
搜索 & 遍历:
// http://oj.leetcode.com/problems/word-ladder/
http://oj.leetcode.com/problems/word-ladder-ii/
广搜:http://oj.leetcode.com/problems/surrounded-regions/