leetcode 126. Word Ladder II解題報告
阿新 • • 發佈:2018-12-15
題目給出了一個單詞表,一個起始單詞和一個結尾單詞,要求找出所有的最短路徑。
因為一開始沒有看到找出所有路徑,寫的是雙向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;
}