feat(bfs, backtracking): new problem formated

This commit is contained in:
2025-11-05 20:44:07 -03:00
parent abefdb4352
commit 3db23b4f54
228 changed files with 6899 additions and 0 deletions

59
sliding-puzzle/src/ac.cpp Normal file
View File

@@ -0,0 +1,59 @@
#include <bits/stdc++.h>
using namespace std;
int N = 6;
unordered_set<string> games;
queue<pair<string, int>> q;
void addGame(int i, int j, string &s)
{
swap(s[i], s[j]);
if (!games.count(s))
q.emplace(s, j);
games.insert(s);
swap(s[i], s[j]);
}
int bfs(string target)
{
q.push({"123450", 5});
int depth = 0;
while (!q.empty())
{
int n = (int)q.size();
while (n--)
{
auto [s, zeroPos] = q.front();
q.pop();
if (s == target)
return depth;
int up = zeroPos - 3, down = zeroPos + 3, left = zeroPos - 1, right = zeroPos + 1;
if (up >= 0)
addGame(zeroPos, up, s);
if (down < N)
addGame(zeroPos, down, s);
if (left >= 0 && zeroPos != 3)
addGame(zeroPos, left, s); // 3 is the down left side
if (right < N && zeroPos != 2)
addGame(zeroPos, right, s); // 2 is the top right side
}
depth++;
}
return -1;
}
int main()
{
vector<string> board(2);
for (int i = 0; i < 2; i++)
{
cin >> board[i];
}
cout << bfs((board[0] + board[1])) << endl;
return 0;
}