[itint5]单词变换

http://www.itint5.com/oj/#42

基本上就是word ladder。直接来BFS,记录前驱。

vector<string> transform(set<string> &dict, string from, string to) {
    vector<string> ans;
    if (from.length() != to.length()) {
        return ans;
    }
    queue<string> que;
    map<string, string> prev_map;
    que.push(from);
    prev_map[from] = "";
    while (!que.empty()) {
        string s = que.front();
        que.pop();
        if (s == to) break;
        for (int i = 0; i < s.length(); i++) {
            char tmp = s[i];
            for (char c = 'A'; c <= 'Z'; c++) {
                if (tmp == c) continue;
                s[i] = c;
                if (dict.find(s) != dict.end()
                    && prev_map.find(s) == prev_map.end()) {
                    que.push(s);
                    prev_map[s] = s;
                    prev_map[s][i] = tmp;
                }
            }
            s[i] = tmp;
        }
    }
    if (prev_map.find(to) == prev_map.end()) return ans;
    string last = to;
    do {
        ans.push_back(last);
        last = prev_map[last];
    } while (last != "");
    for (int i = 0; i < ans.size() / 2; i++) {
        int k = ans.size() - i - 1;
        string tmp = ans[i];
        ans[i] = ans[k];
        ans[k] = tmp;
    }
    return ans;
}

  

posted @ 2014-01-20 00:01  阿牧遥  阅读(184)  评论(0编辑  收藏  举报