标签:
原题链接在这里:https://leetcode.com/problems/word-ladder/
用BFS找最短路径。先把beginWord放入queue中,level 设值为1. 在queue不为空的情况下,从queue中拿出一个word, 设为cur, 同时curCount--.
从cur的第一个字母开始,从a 到 z 挨个替换,若是等于了endWord, 直接返回level+1即可。否则就看set 中是否有这个变形,若是有就把他添加到queue中,并增加计数nextCount. 为了保证不陷入infinite loop, 需同时从set中remove掉这个词。
每当curCont == 0时,说明本层已经扫描完,level++, 同时更新curCount 为nextCount, nextCount 为 0.
AC Java:
public class Solution { public int ladderLength(String beginWord, String endWord, Set<String> wordList) { if(beginWord == null || beginWord.length() == 0 || endWord == null || endWord.length() == 0 || beginWord.length() != endWord.length()){ return 0; } int level = 1; int curCount = 1; int nextCount = 0; LinkedList<String> wordQue = new LinkedList<String>(); wordQue.offer(beginWord); while(!wordQue.isEmpty()){ String cur = wordQue.poll(); curCount--; for(int i = 0; i<cur.length(); i++){ char [] curToChar = cur.toCharArray(); for(char k = ‘a‘; k<=‘z‘; k++){ curToChar[i] = k; String check = new String(curToChar); if(check.equals(endWord)){ return level+1; } if(wordList.contains(check)){ wordQue.offer(check); nextCount++; wordList.remove(check); } } } if(curCount == 0){ level++; curCount = nextCount; nextCount = 0; } } return 0; } }
参考这篇帖子:http://www.cnblogs.com/springfor/p/3893499.html
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4886846.html