题目
错误代码
#include<bits/stdc++.h>
using namespace std;
typedef pair<string, int> PII;
#define x first
#define y second
string aim = "12345678x";
int ans = 0x3f3f3f3f;
unordered_map<string, int> m;
void bfs(string s, int pos)
{
queue<PII> q;
q.push({s, pos});
m[s] = 0;
while(q.size())
{
auto u = q.front();
if(u.x == aim)
{
ans = m[u.x];
return;
}
q.pop();
if(u.y - 3 > 0)
{
string t = u.x;
swap(t[u.y], t[u.y-3]);
if(!m.count(t)) m[t] = m[u.x]+1, q.push({t, u.y-3});
}
if(u.y + 3 < 9)
{
string t = u.x;
swap(t[u.y], t[u.y+3]);
if(!m.count(t)) m[t] = m[u.x]+1, q.push({t, u.y+3});
}
if(u.y/3 == (u.y-1)/3)
{
string t = u.x;
swap(t[u.y], t[u.y-1]);
if(!m.count(t)) m[t] = m[u.x]+1, q.push({t, u.y-1});
}
if(u.y/3 == (u.y+1)/3)
{
string t = u.x;
swap(t[u.y], t[u.y+1]);
if(!m.count(t)) m[t] = m[u.x]+1, q.push({t, u.y+1});
}
}
}
int main()
{
string s = "";
int pos;
for(int i = 0; i < 9; i++)
{
char c;
cin >> c;
if(c == 'x') pos = i;
s = s + c;
}
bfs(s, pos);
if(ans == 0x3f3f3f3f) ans = -1;
cout << ans;
return 0;
}
思考
11个样例过5个TLE,我怀疑是复杂度太高了,枚举的速度太慢了。
不能够用字符串操作吗?但是不用字符串用矩阵进行状态存储也不现实啊。
原因
u.y - 3 >= 0少了=号导致WA
第三个少u.y > 0 导致 TLE
正确代码
#include<bits/stdc++.h>
using namespace std;
typedef pair<string, int> PII;
#define x first
#define y second
string aim = "12345678x";
int ans = 0x3f3f3f3f;
unordered_map<string, int> m;
void bfs(string s, int pos)
{
queue<PII> q;
q.push({s, pos});
m[s] = 0;
while(q.size())
{
auto u = q.front();
if(u.x == aim)
{
ans = m[u.x];
return;
}
q.pop();
if(u.y - 3 >= 0)
{
string t = u.x;
swap(t[u.y], t[u.y-3]);
if(!m.count(t)) m[t] = m[u.x]+1, q.push({t, u.y-3});
}
if(u.y + 3 < 9)
{
string t = u.x;
swap(t[u.y], t[u.y+3]);
if(!m.count(t)) m[t] = m[u.x]+1, q.push({t, u.y+3});
}
if(u.y > 0 && u.y/3 == (u.y-1)/3)
{
string t = u.x;
swap(t[u.y], t[u.y-1]);
if(!m.count(t)) m[t] = m[u.x]+1, q.push({t, u.y-1});
}
if(u.y/3 == (u.y+1)/3)
{
string t = u.x;
swap(t[u.y], t[u.y+1]);
if(!m.count(t)) m[t] = m[u.x]+1, q.push({t, u.y+1});
}
}
}
int main()
{
string s = "";
int pos;
for(int i = 0; i < 9; i++)
{
char c;
cin >> c;
if(c == 'x') pos = i;
s = s + c;
}
bfs(s, pos);
if(ans == 0x3f3f3f3f) ans = -1;
cout << ans;
return 0;
}