最短单词路径
Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Output: 0
Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
题目描述:
??找出一条从beginword到endword的最短路径,每次移动规定为改变一个字符,并且改变之后的字符串必须在 wordList 中。
思路分析:
??采用BFS的思路找最短路径。
代码:
class Solution {
public int ladderLength(String beginWord,String endWord,List<String>wordList){
if(beginWord==null||endWord==null||beginWord.equals(endWord)||!wordList.contains(endWord))
return 0;
Queue<String>q=new LinkedList<>();//构造队列辅助BFS
Set<String>visited=new HashSet<>(); //标记串是否已访问过
Set<String>dict=new HashSet<>(wordList);//wordList中可能出现重复的串
q.offer(beginWord);
visited.add(beginWord);
int len=1;
while(!q.isEmpty()){
int size=q.size(); //当前队列中字符串的个数
for(int s=0;s<size;s++){
String cur=q.poll();
for(int i=0;i<cur.length();i++){ //对当前字符串的每一位进行改变
for(char c='a';c<='z';c++){ //搜索的方式
char []curArray=cur.toCharArray();
char c1=curArray[i];
curArray[i]=c;
String temp=new String(curArray);
if(temp.equals(endWord)){ //到达endword
return len+1;
}
if(!visited.contains(temp)&&dict.contains(temp)){
visited.add(temp);
q.offer(temp);
}
curArray[i]=c1;//每次只能修改一个字母,所以为了进行下一个位置的搜索,需要还原当前位置的字符。
}
}
}
len++; //每进行一次大的循环,长度加一。
}
return 0;
}
}
原文地址:https://www.cnblogs.com/yjxyy/p/11109861.html
时间: 2024-11-05 12:31:45