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,83 @@
#include <iostream>
#include <vector>
#include <set>
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]);
}
//x -> <20>׸<EFBFBD>λ<EFBFBD><CEBB>
void dfs(vector<int> _aim, vector<int> _v, int step, int x){
if(visited.count(_v)) return; // <20><><EFBFBD><EFBFBD><EFBFBD>ظ<EFBFBD>״̬
visited.insert(_v);
// <20><>
if(x >= 3){
vector<int> tmp = _v;
swapUp(tmp, x);
dfs(_aim, tmp, step + 1, x - 3);
}
// <20><>
if(x <= 5){
vector<int> tmp = _v;
swapDown(tmp, x);
dfs(_aim, tmp, step + 1, x + 3);
}
// <20><>
if(x % 3 != 0){
vector<int> tmp = _v;
swapLeft(tmp, x);
dfs(_aim, tmp, step + 1, x - 1);
}
// <20><>
if(x % 3 != 2){
vector<int> tmp = _v;
swapRight(tmp, x);
dfs(_aim, tmp, step + 1, x + 1);
}
//<2F>Ƚ<EFBFBD>
if(_aim == _v){
cout << step << " ";
return;
}
}
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];
}
dfs(aim, arr, 0, pos);
return 0;
}
/*
9
2 6 4 1 3 7 0 5 8
8 1 5 7 3 6 4 0 2
*/