最小操作数(改版)

题目详情:

给了A、B两个单词和一个单词集合Dict,每个的长度都相同。我们希望通过若干次操作把单词A变成单词B,每次操作可以改变单词中的一个字母,同时,新产生的单词必须是在给定的单词集合Dict中。求所有行得通步数最少的修改方法。


   举个例子如下:

Given:

   A = "hit"

   B = "cog"

   Dict = ["hot","dot","dog","lot","log"]

Return

 [

   ["hit","hot","dot","dog","cog"],

   ["hit","hot","lot","log","cog"]

 ]


    即把字符串A = "hit"转变成字符串B = "cog",有以下两种可能:

  1. "hit" -> "hot" ->  "dot" ->  "dog" -> "cog";
  2. "hit" ->  "hot" ->  "lot" ->  "log"  ->"cog"。

答题说明:


  1. A和B相同的情况下不需要做转换,此时直接返回空集;
  2. main函数是为方便你在提交代码之前进行在线编译测试,可不完成。
#include <string>
#include <vector>
#include <iostream>
#include <set>
using namespace std;


class Solution
{
private:
	vector<string> changePath;

public:
	int length;
	int compareStr(string &src,string &dst)
	{
		int count = 0;
		int len = src.length();
		if(src.compare(" ")==0 || dst.compare(" ")== 0)
			return 0;
		for(int i=0;i<len;i++)
		{
			if(src[i] != dst[i])
			{
				count++;
				if(count>1)
					break;
			}
		}
		return count==1?1:0;
	}
	void findLadders(string start, string end, vector<string>& dict)
	{

		changePath.push_back(start);
		if(compareStr(start,end))
		{
			changePath.push_back(end);
			if(changePath.size()<=length)
			{
				length = changePath.size();
				PrintPath(changePath);
				
			}
			changePath.pop_back();
			return ;
		}
		vector<string>::iterator iter;
		for(iter=dict.begin();iter!=dict.end();iter++)
		{
			if(*iter == " ")
				continue;
			string Tempstr = *iter;
			if(compareStr(start,Tempstr))  //找到一个差异为1个字符的单词
			{
				*iter = " ";    //将此单词在字典中删除
				findLadders(Tempstr,end,dict);
				changePath.pop_back();
				*iter = Tempstr;

			}
		}
	}
	void PrintPath(vector<string> &vec)
	{
		for(vector<string>::iterator iter=vec.begin();iter!=vec.end();iter++)
		{
			cout<<*iter;
			if((iter+1) != vec.end())
				cout<<"->";
		}
		cout<<endl;
	}
};



int main()
{   
	Solution aa;
	aa.length = 1000;
	string start = "hit";
	string end = "cog";
	vector<string> dict;
	vector<string> vec;
	dict.push_back("hot");  
	dict.push_back("dot");  
	dict.push_back("dog");  
	dict.push_back("lot");  
	dict.push_back("log"); 
	aa.findLadders(start,end,dict);
	system("pause");
	return 0;
} 


你可能感兴趣的:(最小操作数(改版))