题目链接
https://www.acwing.com/problem/content/description/847/
思路
这道题的难点在于怎么存储状态,因为是一个九宫格,我们其实可以把它压缩成一行,然后用字符串存储,那么这样我们就解决了状态问题,然后我们直接通过find函数或者自己手写匹配,每次找到x的位置,然后将x往四个方向移动,看是否是新状态,当然不能出界,如果我们找到了这个状态那么就返回这个状态的最短交换次数即可,如果没找到最后返回1即可,其实我是先写的DFS,然而DFS好像不太聪明的样子,然后就写了BFS,值得注意的是写BFS的时候,要么手写hash要么就用unordered_map
,使用map是会超时的
代码
#include<bits/stdc++.h>
using namespace std;
//----------------自定义部分----------------
#define ll long long
#define mod 1000000007
#define endl "\n"
#define PII pair<int,int>
int dx[4]={0,-1,0,1},dy[4]={-1,0,1,0};
ll ksm(ll a,ll b) {
ll ans = 1;
for(;b;b>>=1LL) {
if(b & 1) ans = ans * a % mod;
a = a * a % mod;
}
return ans;
}
ll lowbit(ll x){return -x & x;}
const int N = 10;
//----------------自定义部分----------------
int n,m,q;
char a[N][N];
int ans = 0x3f3f3f3f;
bool is_in(int x,int y){
if(x >= 0 && x < 3 && y >= 0 && y < 3) return true;
return false;
}
map<string,bool> vis;
string end_state="12345678x";
void dfs(string state,int step){
if(state == end_state){
ans = min(ans,step);
cout<<ans<<endl;
return;
}
if(vis[state]) return;
vis[state] = true;
int k = state.find('x');
int x = k/3,y = k % 3;
for(int i = 0;i < 4; ++i) {
int nx = x + dx[i];
int ny = y + dy[i];
int l = nx * 3 + ny;
string nexs = state;
swap(nexs[l],nexs[k]);
if(is_in(nx,ny) && !vis[nexs]){
dfs(nexs,step+1);
}
}
}
int bfs(string start){
queue<string> que;
que.push(start);
unordered_map<string,int> dis;
dis[start] = 0;
while(!que.empty()){
string p = que.front();
que.pop();
int distance = dis[p];
if(p == end_state) return distance;
int k = p.find('x');
int x = k / 3,y = k % 3;
for(int i = 0;i < 4; ++i) {
int nx = x + dx[i];
int ny = y + dy[i];
if(nx >= 0 && nx < 3 && ny >= 0 && ny < 3) {
swap(p[nx * 3 + ny],p[k]);
if(!dis[p]){
dis[p] = distance + 1;
que.push(p);
}
swap(p[nx * 3 + ny],p[k]);
}
}
}
return -1;
}
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
string start;
char c;
for(int i = 0;i < 9; ++i) cin>>c,start+=c;
//DFS----------------------DFS
// dfs(start,0);
// cout<<ans<<endl;
//DFS----------------------DFS
//BFS----------------------BFS
cout<<bfs(start)<<endl;
//DFS----------------------DFS
return 0;
}