[leetcode] Word Ladder

图解LeetCode:Word Ladder 文章目录思考过程建立索引代码实现总结 这是LeetCode的第127号题目Word Ladder,也就是单词梯子,那这个题目是什么意思呢? 给定两个单词,一个为开头单词beginWord,一个为结尾单词endWord,并且给定一个单词列表,找出从开头单词到结尾单词的最短转换路径,转换规则是这样的: 一次只能转换单词中的一个字符 每次转换后的单词必须存在于单词列表中 比如给定开头单词“hit”,... 阅读详情

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

  1. Only one letter can be changed at a time
  2. 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.
可以把这道题变成一个搜索单源最短路径的问题。利用DFS搜索

class Solution {
public:
    int ladderLength(string start, string end, unordered_set<string> &dict) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		dict.erase(start);
		dict.erase(end);
		vector<string> words;
		words.push_back(start);
		words.insert(words.end(),dict.begin(),dict.end());
		words.push_back(end);
		int length=words.size();
		int wordlength=start.size();
		int count,min=INT_MAX;
		bool *flag=new bool[length];
		memset(flag,false,sizeof(bool)*length);
		int (*graph)[10000]=new int[length][10000];
		for(int i=0 ; i<length ; i++){
			graph[i][i]=0;
			for(int j=i+1 ; j<length ; j++){
				count=0;
				for(int k=0 ; k<wordlength ; k++){
					if(words[i][k]!=words[j][k])
						count++;
				}
				graph[i][j]=count;
				graph[j][i]=count;
			}
		}//form the graph;
		count=1;
		flag[0]=true;
		DFS(graph,0,length-1,flag,length,count,min);
		return min==INT_MAX?0:min;
	}
	void DFS(int (*g)[10000], int i, const int j, bool *flag, int n, int& count, int& min){
		if(i==j){
			if(count<min)
				min=count;
			return;
		}
		for(int k=0 ; k<n ; k++){
			if(g[i][k]==1 && !flag[k]){
				flag[k]=true;
				count++;
				DFS(g,k,j,flag,n,count,min);
				count--;
				flag[k]=false;
			}
		}
	}
};
但是过不了大数据,把DFS改成BFS试试。
class Solution {
    typedef pair<int,int> path;
public:
	int ladderLength(string start, string end, unordered_set<string> &dict) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		dict.erase(start);
		dict.erase(end);
		vector<string> words;
		words.push_back(start);
		words.insert(words.end(),dict.begin(),dict.end());
		words.push_back(end);
		int length=words.size();
		int wordlength=start.size();
		int count,min=INT_MAX;
		bool *flag=new bool[length];
		memset(flag,false,sizeof(bool)*length);
		int (*graph)[10000]=new int[length][10000];
		for(int i=0 ; i<length ; i++){
			graph[i][i]=0;
			for(int j=i+1 ; j<length ; j++){
				count=0;
				for(int k=0 ; k<wordlength ; k++){
					if(words[i][k]!=words[j][k])
						count++;
				}
				graph[i][j]=count;
				graph[j][i]=count;
			}
		}//form the graph;
		queue<pair<int,int> > bfs;
		bfs.push(make_pair(0,1));
		while(!bfs.empty()){
			path head=bfs.front();
			flag[head.first]=true;
			if(head.first==length-1)
				return head.second;
			for(int i=0 ; i<length ; i++){
				if(graph[head.first][i]==1 && !flag[i])
					bfs.push(path(i,head.second+1));
			}
			bfs.pop();
		}
		if(bfs.empty())
			return 0;
	}
};

我的这种先弄一个二维矩阵的方法好像不被允许,提示内存超了。主要的时间耗费在了前面矩阵赋值上面,那么就不要先计算出这种矩阵,边BFS边比较:
class Solution {
public:
	int ladderLength(string start, string end, unordered_set<string> &dict) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		//BFS(because all edge is 1) to find the minimum path
		//O(n*len*26)
		queue<pair<string,int>> q;
		unordered_set<string> visited;
		q.push(make_pair(start, 1));
		visited.insert(start);
		while (!q.empty())	{
			string curStr = q.front().first;
			int curStep = q.front().second;
			q.pop();
			for (int i = 0; i < curStr.size(); ++i)	{
				string tmp = curStr;
				for (int j = 0; j < 26; ++j) {
					tmp[i] = j+'a';
					if(tmp == end)
						return curStep+1;
					if(visited.find(tmp) == visited.end() && dict.find(tmp) != dict.end()) {
						q.push(make_pair(tmp, curStep+1));
						visited.insert(tmp);
					}
				}
			}
		}
		return 0;
	}
};




LeetCode126—Word Ladder II 阅读详情

相关推荐

PyTorch实战:从零构建CNN图像分类模型

卷积神经网络(CNN)作为计算机视觉的核心架构,通过局部连接和权值共享机制高效处理图像数据。其核心组件包括卷积层、池化层和全连接层,其中PyTorch的动态计算图特性为CNN实现提供了灵活的开发环境。在工程实践中,使用CIFAR-10这类标准数据集可以快速验证模型性能,而数据增强和批归一化等技术能有效提升模型泛化能力。通过PyTorch实现CNN不仅能够掌握图像分类的基本原理,还能为后续迁移学习和复杂视觉任务打下基础,特别是在结合Adam优化器和学习率调度策略后,模型收敛速度和准确率都能得到显著提升。

weixin_42405592的博客 318

LeetCode——Word Ladder II

链接:http://leetcode.com/onlinejudge#question_126 原题: Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that: Only one

niaokedaoren的专栏 8948

谈谈SAP顾问的几个发展趋势

大家新年好,今天想聊一下对SAP顾问发展趋势的一些个人见解。过去10多年得益于我国的经济发展,外资不断加大在中国的投资和中国企业的发展,SAP顾问行业得到了很大的发展和壮大。那么未来几年SAP顾问的职业发展到底怎么样呢?

syounger的专栏 2514

leetcode之word-ladder

leetcode之word-ladder 题目 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 Ea...

此心光明,亦复何言~ 529

Android开发者必看:火山引擎API验签实战,5分钟搞定年龄变化接口调用

本文为Android开发者提供火山引擎API验签实战指南,重点解析HMAC-SHA256签名算法实现,并以年龄变化接口为例展示完整调用流程。通过OkHttp封装和性能优化建议,帮助开发者5分钟内快速集成火山引擎人像处理功能,解决API调用中的签名验证、参数编码等核心问题。

weixin_30342209的博客 317

ISO26262功能安全--产品开发过程

目录 1.总体理解 2.概念阶段——吹牛,我们是打草稿的 2.1 相关项定义 2.2 HARA分析 2.3 功能安全目标 2.4 安全需求与安全概念 3. 系统阶段——闭门造神车,我们开始修炼 3.1 技术安全需求(TSC) 3.2 系统架构设计 3.3 安全分析与独立性分析 3.4 软硬件接口(HSI) 4. 硬件阶段——苦其心志,苦练经骨 4.1 硬件架构...

AgingMoon的博客 1万+

LeetCode127—Word Ladder

LeetCode127—Word Ladder

上善若水 2703

AI训练师团队管理运营思路

工具运营AI训练师主要是支撑运营,协助算法和运营提高托管机器人的解决能力,以协助降低业务场景熔断与优化场景识别为核心运营目标,通过算法聚类、标注分析等方式,结合业务知识,提供精准、清晰的标注数据和解决方案,确保训练效果满足需求。过程中需要与算法、运营一块参与模型搭建和数据验收,并且负责核心指标和数据日常的跟踪维护。④针对知识库已有意图进行梳理和分析,反馈运营评估缺失或合并意图优化方向。③对语料数据进行挖掘、清洗,解除缠绕、冗余等问题导致的未识别。①线上case分析,及时发现识别问题导致的托管熔断问题。

qq_25438419的博客 1085

LeetCode-126. Word Ladder II [C++][Java]

Given two words,beginWordandendWord, and a dictionarywordList, returnall theshortest transformation sequencesfrombeginWordtoendWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words[beginWord,

贫道绝缘子的博客 1131

数字IC笔记-低功耗技术

传统的降低Power的方法主要有: 1.门控时钟技术(clock gating) 2.多阈值电压技术(MultiShreshold) 3.动态电压频率调节技术(DVFS) 目前有以下几种低功耗技术: 1.多电压技术(Multi-Voltage) 2.MTCOMS Power Gating 技术(多阈值功耗控制技术),比如基带部分中的2G、3G、CDMA、LTE等通过awake—>sleep—>awake的方式间歇式的打开或关断其电源,power gating 可以完全关掉dynamic的pow

sinat_41774721的博客 1932

Lammps实现Ar的沸腾过程(包含in文件)

Lammps实现简单的沸腾过程

Rockyoung 3503

LeetCode 127. Word Ladder II

感觉思路不像网上一些博主说的那么复杂... 用dis(map<string, int>类型)记录每个单词离start的距离,通过BFS记录每个单词的前继单词paths(map<string, vector<string>>); 再通过paths信息从end递归(可以理解为DFS), 求出到end的道路即可。

Stephen Wong的专栏 875

从4A架构的角度出来 帮我分析一下:数字化转型深水区:企业架构如何成为价值重构的核心引擎?

4A 架构的本质是构建企业的数字神经系统,通过业务感知、数据传输、决策执行、技术支撑的闭环,实现从效率提升到生态重构的质变。正如华为通过该架构实现全球研发资源统一调度,某零售集团借此打造线上线下融合的新零售体系,当业务、数据、应用、技术四个维度形成共振时,企业将获得持续进化的数字免疫力,在不确定的市场环境中保持韧性生长。这一过程不仅需要技术工具的升级,更依赖组织文化的变革 —— 从 “部门墙” 到 “能力网” 的转型,才是数字化转型深水区的终极挑战。

金牌架构师 1046

leetcode 126. Word Ladder II

leetcode 126. Word Ladder II   写这一题 真的非常适合复习bfs与dfs啊 import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.ut

独钓寒江雪 559

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

leetcode 126 Word Ladder II

题目连接 https://leetcode.com/problems/word-ladder-ii/ Word Ladder II Description Given two words (beginWordandendWord), and a dictionary's word list, find all shortest transformation sequenc...

dong12276的博客 314

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

leetcode 126. Word Ladder II

今天这篇笔记讲讲一直都弄得不是很清楚的回溯算法。回溯写法用于dfs比较常见,由于深度优先,如果搜完之后还需要继续搜索,那么就只好往前回溯了。深度优先之所以需要这样遍历,是为了不重复搜索,特别是这种树形结构的。在形式上比较像bfs,但实质上是dfs,因为一定是在一个搜索路径下走完,才来寻找其他的路径。 这一题下面这种解法确实有一些难度,先是用bfs来建立树,并且利用层次进行标明,然后再利用dfs反

独钓寒江雪 440

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Word Ladder II -- LeetCode

Word Ladder II -- LeetCode

qq_44939824的博客 139

LeetCode - 127. Word Ladder & 126 (BFS)

LeetCode - 127. Word Ladder &amp;amp; 126 (BFS) LeetCode - 127. Word Ladder LeetCode - 126. Word LadderII LeetCode - 127. Word Ladder 题目链接 题目 解析 两种解法: 单向BFS和双向BFS(Bidrectional BFS)。 单向BFS: 首先将wordDic...

zxzxin的博客~ 573

Leetcode OJ 127 Word Ladder [Medium]

Leetcode OJ 127 Word Ladder   题目描述: Given two words (beginWord and endWord), and adictionary's word list, find the length of shortest transformation sequencefrom beginWord to endWord, such that:

大吱的博客 525

leetcode Word Ladder

题目连接 https://leetcode.com/problems/word-ladder/ Word Ladder Description Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation seq...

dong12276的博客 192

【leetcode】【hard】126. Word Ladder II​​​​​​​

126. Word Ladder II Given two words (beginWordandendWord), and a dictionary's word list, find all shortest transformation sequence(s) frombeginWordtoendWord, such that: Only one letter can be c...

lemonade13的博客 174

126. Word Ladder II 、 127. Word Ladder(leetcode BFS+DFS)

127. Word Ladder 题目地址https://leetcode.com/problems/word-ladder/acac代码餐卡 博主:陆草纯 地址:http://www.cnblogs.com/ganganloveu/p/4125695.html 直接采用bfs, 注意判重,解map,set结构struct Node{ string word; int len

master-dragon的专栏 871

【重点BFS】LeetCode 127. Word Ladder

Solution1: 利用BFS做但是内存溢出未能AC,还是记录一下 class Solution { public: int ladderLength(string beginWord, string endWord, vector&amp;amp;amp;amp;amp;amp;lt;string&amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp; wordList) { if (find(

Allenlzcoder的博客 448
上一篇: 六级520,这么吉祥的数字纪念一下
下一篇: [leetcode] Word Ladder II
和道一文字JC
博客等级 码龄19年 24粉丝 178原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值