标签:wordList Word words sequence int Ladder beginWord endWord LeetCode
A transformation sequence from word beginWord
to word endWord
using a dictionary wordList
is a sequence of words beginWord -> s1 -> s2 -> ... -> sk
such that:
- Every adjacent pair of words differs by a single letter.
- Every
si
for1 <= i <= k
is inwordList
. Note thatbeginWord
does not need to be inwordList
. sk == endWord
Given two words,beginWord
andendWord
, and a dictionarywordList
, return the number of words in the shortest transformation sequence frombeginWord
toendWord
, or 0 if no such sequence exists.
Solution
注意到每次只能变一个字符,所以我们可以遍历每一个位置,将其设置为 \(\#\),然后用 \(map\) 映射到 \(string\) 的 \(vector\) 里面。所以我们就可以利用 \(BFS\) 的方式,其中队列里面存储 \(pair(str, step)\)
点击查看代码
class Solution {
private:
unordered_map<string, vector<string>> mp;
queue<pair<string, int>> q;
unordered_map<string,int> vis;
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
if(count(wordList.begin(), wordList.end(), endWord)==0)
return 0;
int n = wordList.size();
wordList.push_back(beginWord);
int m = wordList[0].size();
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
string tmp = wordList[i].substr(0,j)+'#'+wordList[i].substr(j+1,m-j-1);
mp[tmp].push_back(wordList[i]);
}
}
q.push({beginWord, 1});
while(!q.empty()){
auto f = q.front();q.pop();
vis[f.first]=1;
string cur = f.first;
int cur_step = f.second;
for(int i=0;i<m;i++){
string tmp = cur.substr(0,i)+'#'+cur.substr(i+1,m-i-1);
for(auto t:mp[tmp]){
if(!vis[t]){
if(t==endWord)return cur_step+1;
q.push({t, cur_step+1});
}
}
}
}
return 0;
}
};
标签:wordList,Word,words,sequence,int,Ladder,beginWord,endWord,LeetCode 来源: https://www.cnblogs.com/xinyu04/p/16593559.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。