注解
1、C++的string操作速度很慢,用string本题会超时!改用int数组。要学会字符串,整型等类型之间的转换。
2、BFS,从一个数字开始,依次进行:每位数字加一,每位数字减一,交换两相邻数字,这三种操作。
3、BFS的同时要记录曾经在队列中出现的数字,避免重复导致内存溢出。具体方法是增加一个visit数组,记录访问过的四位数。
代码
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int LEN = 4;
const int MAXN = 10001;
int visit[MAXN];
struct Node {
int num[LEN];
int step;
};
Node startNode;
Node endNode;
int arrayToInt(int a[LEN]) {
return a[0]*1000+a[1]*100+a[2]*10+a[3];
}
void bfs() {
queue<Node> q;
startNode.step = 0;
q.push(startNode);
visit[arrayToInt(startNode.num)] = 1;
while(q.size()>0) {
Node top = q.front();
q.pop();
int flag = 1;
for(int i=0; i<LEN; i++) {
if(top.num[i]!=endNode.num[i]) {
flag = 0;
break;
}
}
if(flag) {
printf("%d\n", top.step);
break;
} else {
int newStep = top.step + 1;
for(int i=0; i<LEN; i++) {
Node newNode;
newNode.step = newStep;
int tmp[LEN];
for(int j=0; j<LEN; j++) {
newNode.num[j] = top.num[j];
}
if(newNode.num[i]==9) {
newNode.num[i] = 1;
} else {
newNode.num[i] += 1;
}
if(visit[arrayToInt(newNode.num)]==0) {
q.push(newNode);
visit[arrayToInt(newNode.num)] = 1;
}
}
for(int i=0; i<LEN; i++) {
Node newNode;
newNode.step = newStep;
int tmp[LEN];
for(int j=0; j<LEN; j++) {
newNode.num[j] = top.num[j];
}
if(newNode.num[i]==1) {
newNode.num[i] = 9;
} else {
newNode.num[i] -= 1;
}
if(visit[arrayToInt(newNode.num)]==0) {
q.push(newNode);
visit[arrayToInt(newNode.num)] = 1;
}
}
for(int i=0; i<LEN-1; i++) {
Node newNode;
newNode.step = newStep;
int tmp[LEN];
for(int j=0; j<LEN; j++) {
newNode.num[j] = top.num[j];
}
swap(newNode.num[i], newNode.num[i+1]);
if(visit[arrayToInt(newNode.num)]==0) {
q.push(newNode);
visit[arrayToInt(newNode.num)] = 1;
}
}
}
}
}
int main() {
int T;
scanf("%d", &T);
for(int i=0; i<T; i++) {
memset(visit, 0, sizeof(visit));
int a1, a2;
scanf("%d", &a1);
scanf("%d", &a2);
startNode.num[0] = a1/1000;
startNode.num[1] = (a1/100)%10;
startNode.num[2] = (a1/10)%10;
startNode.num[3] = a1%10;
endNode.num[0] = a2/1000;
endNode.num[1] = (a2/100)%10;
endNode.num[2] = (a2/10)%10;
endNode.num[3] = a2%10;
bfs();
}
return 0;
}