Word Transform

/***
18.10
Given two words of equal length that are in a dictionary, write a method to
transform one word into another word by changing only one letter at a time. The
new word you get in each step must be in the dictionary.

EXAMPLE
input: DAMP, LIKE
output: DAMP->LAMP->LIMP->LIME->LIKE
***/

#include<iostream>
#include<string>
#include <vector>

using namespace std;

bool isword(string s) {
       string dic[] = {"damp", "lamp", "limp", "lime", "like", "lake"};
       int sz = sizeof(dic) / sizeof(string);
       int i = 0;
       while (i<sz)
       {
              if (dic[i] == s)
              {
                     return true;
              }
              i++;
       }
       return false;
}

void wordtransform(string str1, string str2, bool *s, vector<string> v, vector<vector<string>> *path) {
       if(str1 == str2) {
              path->push_back(v); 
              return;
       }

       for(int i = 0; i<str2.size(); i++) {
              if(s[i]) {
                     string t = str1;
                     t[i] = str2[i];
                     if(isword(t)) {
                           s[i] = false;
                           v.push_back(t);
                           wordtransform(t, str2, s, v, path);
                           v.pop_back();
                           s[i] = true;
                     }
              }
       }
       return;
}

void main() {
      
       string str1 = "damp";
       string str2 = "like";
       bool s[4];
       memset(s, 1, 4);
       vector<string> str;
       vector<vector<string>> path;

       str.push_back(str1);
       wordtransform(str1, str2, s, str, &path);

       for (int i = 0; i<path.size(); i++)
       {
              for(int j = 0; j<path[i].size(); j++)
                     cout<<path[i][j]<<"->";
       }
}



Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs