feat(bfs): new problem formated

This commit is contained in:
2025-11-05 23:33:57 -03:00
parent 3db23b4f54
commit e4a9cd474f
20 changed files with 6672 additions and 0 deletions

View File

@@ -0,0 +1,72 @@
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
string beginWord, endWord;
cin >> beginWord >> endWord;
unordered_set<string> words;
for (int i = 0; i < n; i++)
{
string s;
cin >> s;
words.insert(s);
}
words.insert(beginWord);
unordered_map<string, list<string>> adj;
for (auto &word : words)
{
for (int j = 0; j < m; j++)
{
string aux = word;
for (char c = 'a'; c <= 'z'; c++)
{
aux[j] = c;
if (words.count(aux))
{
adj[word].push_back(aux);
}
}
}
}
queue<string> q;
unordered_set<string> seen;
q.push(beginWord);
seen.insert(beginWord);
int depth = 1;
while (!q.empty())
{
int nodes = q.size();
while (nodes--)
{
string s = q.front();
q.pop();
if (s == endWord)
{
cout << depth << endl;
return 0;
}
for (auto &t : adj[s])
{
if (!seen.count(t))
{
q.push(t);
seen.insert(t);
}
}
}
depth++;
}
cout << 0 << endl;
return 0;
}