[leetcode] word ladder

本文提供了一种使用广度优先搜索(BFS)解决LeetCode上单词梯问题的有效方法。该问题要求从一个单词开始,通过替换字母的方式转换到另一个目标单词,每次只能替换一个字母且中间过程中的所有单词都必须存在于给定的字典中。通过构建邻接矩阵并采用BFS算法,我们实现了寻找最短转换路径长度的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Q: Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

Only one letter can be changed at a time
Each intermediate word must exist in the dictionary

For example,

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Note:

Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.


http://leetcode.com/onlinejudge#question_127


Solution:

Much more easier than word ladder 2. BFS search.



public class Solution {
public int ladderLength(String start, String end, HashSet<String> dict) {
// Start typing your Java solution below
// DO NOT write main() function

dict.add(start);
dict.add(end);

// calcualte ajacent matrix
HashMap<String, ArrayList<String>> adj = new HashMap<String, ArrayList<String>>();
for(String str : dict){
char [] chars = str.toCharArray();
for(int i=0;i<start.length();i++){
char old = chars[i];
for(char c = 'a' ; c <= 'z'; c++){
if(c == old) continue;
chars[i] = c;
String newstr = new String(chars);
if(dict.contains(newstr)){
ArrayList<String> neighbours = adj.get(str);
if(neighbours == null){
neighbours = new ArrayList<String>();
neighbours.add(newstr);
adj.put(str, neighbours);
}else {
neighbours.add(newstr);
}
}
}
chars[i] = old;
}
}

HashSet<String> visited = new HashSet<String>();
LinkedList<Node> queue = new LinkedList<Node>();
queue.add(new Node(1, start));
visited.add(start);
int pathLen = 0;

while(!queue.isEmpty()){
Node n = queue.pollFirst();
if(n.str.equals(end)){
pathLen = n.level;
break;
}else {
ArrayList<String> neighbours = adj.get(n.str);
if(neighbours == null || neighbours.isEmpty()) continue;
for(String s : neighbours){
if(! visited.contains(s)){
Node p = new Node(n.level+1, s);
queue.add(p);
visited.add(s);
}
}
}
}

return pathLen;
}



public class Node {
public int level;
public String str;
Node(int l, String s){
str = s;
level = l;
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值