feat(bfs): new problem formated
This commit is contained in:
72
conversor-fonetico-generico/src/ac.cpp
Normal file
72
conversor-fonetico-generico/src/ac.cpp
Normal 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;
|
||||
}
|
||||
Reference in New Issue
Block a user