题目给出了一个单词表,一个起始单词和一个结尾单词,要求找出所有的最短路径。
因为一开始没有看到找出所有路径,写的是双向BFS搜索,后面改了一下,使用BFS进行查找。
将原本的parent数组改为了vector<vector<string>>
以满足查找所有最短路径的需求。在BFS的过程中,通过遍历单词表的形式搜索可行的单词。对于可行的单词,如果没有访问过,则将其入队准备进行访问;如果已经访问过,检查其深度是否为当前深度+1,如果是的话,则可能为最短路的一条岔路。
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <queue>
#include <algorithm>
using namespace std;
class Solution {
public:
bool diff(string a,string b){
if(a.length()!=b.length())
{
return false;
}
int counting = 0;
for(unsigned int i=0;i<a.length();i++)
{
if(a[i]!=b[i])
{
counting++;
if(counting>1)
{
return false;
}
}
}
if(counting == 1)
{
return true;
}
else
{
return false;
}
}
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
queue<string> q;
//给每个字符串做标记
int counting = 0;
map<string,int> lookup;
vector<int> depth;//BFS深度
vector<vector<string>> parent;//其他同等深度下链接到这个点的点
q.push(beginWord);
lookup[beginWord] = 0;
depth.push_back(0);
parent.push_back(vector<string>());
while(!q.empty())
{
string point = q.front();
q.pop();
int id = lookup[point];
//cout<<point<<" enter BFS search, its number is "<<id<<". It's depth is"<<depth[id]<<endl;//debug
//遍历单词表,找到可行的解
for(unsigned int i = 0;i<wordList.size();i++)
{
if(diff(wordList[i],point))
{
if(lookup.find(wordList[i])==lookup.end())//目标节点尚未登记,登记信息,加入。
{
counting++;
q.push(wordList[i]);
lookup[wordList[i]]=counting;
depth.push_back(depth[id]+1);
vector<string> now;
now.push_back(point);
parent.push_back(now);
//cout<<"It found new node "<<wordList[i]<<" and its number is"<<counting<<" with it's depth"<<depth[counting]<<endl;
}
else if(depth[lookup[wordList[i]]] == depth[id]+1)//目标节点已经登记,查看距离信息是否符合
{
parent[lookup[wordList[i]]].push_back(point);
//cout<<"It also add to "<<wordList[i]<<endl;
}
}
}
}
vector<vector<string>> ans;
if(lookup.find(endWord)==lookup.end())
return ans;
else
{
vector<string> answer;
getResult(endWord,answer,beginWord,wordList,ans,lookup,parent);
for(unsigned int i=0;i<ans.size();i++)
{
reverse(ans[i].begin(),ans[i].end());
}
return ans;
}
}
void getResult(string current,vector<string> ans,string& endPoint,vector<string>& wordList,vector<vector<string>>& result,map<string,int>& lookup,vector<vector<string>>& parent)
{
ans.push_back(current);
if(current == endPoint)
{
result.push_back(ans);
return;
}
else
{
for(unsigned int i = 0;i<parent[lookup[current]].size();i++)
{
getResult(parent[lookup[current]][i],ans,endPoint,wordList,result,lookup,parent);
}
}
}
};
/*
朴素思想:
目标找到所有的最短路径
BFS搜索,允许链表
使用map作为parent,同时提供对于BFS深度的记录
函数diff() 接受两个string,判断它们的差值是否为一个字母
*/
int main(void)
{
vector<string> l;
l.push_back("hot");
l.push_back("dot");
l.push_back("dog");
l.push_back("lot");
l.push_back("log");
l.push_back("cog");
Solution s;
vector<vector<string>> ans(s.findLadders("hit","cog",l));
for(unsigned int i = 0 ;i<ans.size();i++)
{
for(unsigned int j=0;j<ans[i].size();j++)
{
cout<<ans[i][j]<<" ";
}
cout<<endl;
}
return 0;
}