Altered Algorithm

This commit is contained in:
e2hang
2025-09-01 19:49:15 +08:00
parent e162486df1
commit 9c30eb42e2
15 changed files with 954 additions and 0 deletions

View File

@@ -0,0 +1,109 @@
#include <iostream>
#include <vector>
#include <deque>
#include <set>
#include <utility>
using namespace std;
set<vector<int>> visited;
//<2F><><EFBFBD><EFBFBD>Ĭ<EFBFBD>ϾŹ<CFBE><C5B9><EFBFBD>
void swapUp(vector<int>& _v, int _i){
if(_i == 0 || _i == 1 || _i ==2 ) return;
swap(_v[_i], _v[_i - 3]);
}
void swapDown(vector<int>& _v, int _i){
if(_i == 6 || _i == 7 || _i ==8 ) return;
swap(_v[_i], _v[_i + 3]);
}
void swapLeft(vector<int>& _v, int _i){
if(_i == 0 || _i == 3 || _i ==6 ) return;
swap(_v[_i], _v[_i - 1]);
}
void swapRight(vector<int>& _v, int _i){
if(_i == 2 || _i == 5 || _i ==8 ) return;
swap(_v[_i], _v[_i + 1]);
}
//pos -> <20>׸<EFBFBD>λ<EFBFBD><CEBB>
int bfs(vector<int> _aim, vector<int> _v){
deque<pair<vector<int>, int>> q;
q.push_back({_v, 0});
visited.insert(_v);
while(!q.empty()){
auto tmp = q.front(); q.pop_front();
vector<int> tmpv = tmp.first;
int step = tmp.second;
if(tmpv == _aim) return step;
int x;
for(int i = 0; i < tmpv.size(); i++){
if(tmpv[i] == 0) {
x = i;
break;
}
}
// <20><>
if(x >= 3){
vector<int> tmps = tmpv;
swapUp(tmps, x);
if(!visited.count(tmps)){
visited.insert(tmps);
q.push_back({tmps, step + 1});
}
}
// <20><>
if(x <= 5){
vector<int> tmps = tmpv;
swapDown(tmps, x);
if(!visited.count(tmps)){
visited.insert(tmps);
q.push_back({tmps, step + 1});
}
}
// <20><>
if(x % 3 != 0){
vector<int> tmps = tmpv;
swapLeft(tmps, x);
if(!visited.count(tmps)){
visited.insert(tmps);
q.push_back({tmps, step + 1});
}
}
// <20><>
if(x % 3 != 2){
vector<int> tmps = tmpv;
swapRight(tmps, x);
if(!visited.count(tmps)){
visited.insert(tmps);
q.push_back({tmps, step + 1});
}
}
}
return -1; // <20>޽<EFBFBD>
}
int main(){
int n;
cin >> n;
vector<int> arr(n, -1);
vector<int> aim(n, -1);
int pos;
for(int i = 0; i < n; i++){
cin >> arr[i];
if(arr[i] == 0) pos = i;
}
for(int i = 0; i < n; i++){
cin >> aim[i];
}
cout << bfs(aim, arr) << endl;
return 0;
}
/*
9
2 6 4 1 3 7 0 5 8
8 1 5 7 3 6 4 0 2
*/