Commit 12520e09 authored by Sadman Kazi's avatar Sadman Kazi 🎸

Solve word ladder

parent 62325c54
1
hit cog
6
hot dot dog lot log cog
#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;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment