Commit 12520e09 authored by Sadman's avatar Sadman
Browse files

Solve word ladder

parent 62325c54
Loading
Loading
Loading
Loading

127/input.txt

0 → 100644
+4 −0
Original line number Diff line number Diff line
1
hit cog
6
hot dot dog lot log cog

127/word_ladder.cpp

0 → 100644
+93 −0
Original line number Diff line number Diff line
#include <iostream>
#include <vector>
#include <queue>

using namespace std;

class Node {
public:
    std::vector<Node*> adj;
    std::string value;
    bool marked;
    static int length;

    Node(string str) : value(str), marked(false) {}
    ~Node() { adj.clear(); }
};

int Node::length = 0;

int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
    std::vector<Node*> left, right;
    Node::length = beginWord.length();

    Node* start = new Node(beginWord);
    left.push_back(start);

    for (string word : wordList) {
        left.push_back(new Node(word));
    }

    for (Node* parent : left) {
        for (Node* child : left) {
            int diff = 0;
            for (int i = 0; i < Node::length; i++) {
                if (parent->value[i] != child->value[i]) {
                    diff++;
                }
            }
            if (diff == 1) {
                parent->adj.push_back(child);
            }
        }
    }

    // run BFS to find the node
    std::queue<Node*> bfs;

    start->marked = true;
    bfs.push(start);
    bfs.push(nullptr);
    int depth = 1;

    while (!bfs.empty()) {
        Node* current = bfs.front();
        bfs.pop();
        if (current == nullptr) {
            depth++;
            bfs.push(nullptr);
            if (bfs.front() == nullptr) return 0;
        } else if (current->value.compare(endWord) == 0) {
            return depth;
        } else {
            for (Node* child : current->adj) {
                if (child->marked == false) {
                    bfs.push(child);
                    child->marked = true;
                }
            }
        }
    }

    return 0;
}

int main () {
    int iter;
    std::string start, end;

    std::cin >> iter;

    for (int i = 0; i < iter; i++) {
        std::cin >> start >> end;
        int size;
        std::string elem;
        std::vector<std::string> list;
        std::cin >> size;
        for (int j = 0; j < size; j++) {
            std::cin >> elem;
            list.push_back(elem);
        }
        std::cout << ladderLength(start, end, list) << std::endl;
    }
}