本文最后更新于583 天前,其中的信息可能已经过时,如有错误请发送邮件到tomding1065@gmail.com
https://www.programmercarl.com/kamacoder/0110.%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%8E%A5%E9%BE%99.html
1.本题的思路很清晰就是最近做的题由于是从回溯算法过来的,所以对dfs会更有好感所以最近的题基本上都使用的是dfs除了一些指定要用bfs的题之外都用的dfs所以本题字符串要求最短路径,我就知道逃不掉了,因为bfs只要求出来就一定是最短路径所以,本题的bfs思路其实也很简单,厘清思路就可以写出来。set用来储存中间的字符串然后还可以去重,map储存访问过的节点,然后也存储他到起始位置之间的路径长度。
CPP
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
string beginStr, endStr, str;
cin >> beginStr >> endStr;
unordered_set<string> strSet;
for(int i = 0; i < n; i++){
cin >> str;
strSet.insert(str);
}
queue<string> que;
unordered_map<string, int>visitedMap;
que.push(beginStr);
visitedMap.insert(pair<string, int>(beginStr, 1));
while(!que.empty()){
string word = que.front();
que.pop();
int path = visitedMap[word];
for(int i = 0; i < word.size(); i++){
string newWord = word;
for(int j = 0; j < 26; j++){
newWord[i] = j + 'a';
if(newWord == endStr){
cout << path + 1 << endl;
return 0;
}
if(strSet.find(newWord) != strSet.end() && visitedMap.find(newWord) == visitedMap.end()){
visitedMap.insert(pair<string, int>(newWord, path + 1));
que.push(newWord);
}
}
}
}
cout << 0 <<endl;
}