您的位置:首页 > 运维架构

bfs ZOJ 2416 Open the Lock

2010-09-09 17:18 232 查看
第一次写DFS,这题不难,基本照着今早找到那个程序的思路敲出来的,但是搞了好久才AC掉, 一开始就超时, 到后来就WA,纳闷了很久

DFS主要就是

有个flag数组,储存所有可能状态,标记是否查找过

设定好操作集,对数据进行的操作

一般思路就是

开始有一个Queue, 对现在的每一个状态的所有可能不断地push进队列, 再检查, 直到找到答案

经验:

C++里面那个string对象作为参数传入时,不是引用的,而是副本,这点和java不同,java除了基本类型外,所有对象都是引用

每次bfs前, 先清理Queue,以防上次留下的数据导致出错

Open the Lock

#include <iostream>
#include <string>
#include <queue>
using namespace std;

struct node
{
string a;
int step;
};
//标记数组,题目中有1111~9999这么多个数,用这些数作为下标
int flag[10000] = {0};
node N,P;
string c, b;
queue<node>Q;
//题目中有三种操作,+,—,交换
string adddigit(string , int );
string minusdigit(string , int );
string changedigit(string , int );

void bfs();

int main()
{
int num;
cin >> num;
for (int i = 0; i < num; i++)
{
cin >> c >> b;

for (int i = 1111; i < 10000; i++)
flag[i] = 0;

bfs();
}
return 0;
}

void bfs()
{
N.a = c;N.step = 0;
//bfs前清空队列
while(!Q.empty())
Q.pop();

Q.push(N);
flag[atoi(N.a.c_str())] = 1;

while (!Q.empty())
{
N = Q.front();
Q.pop();

if (N.a == b)
break;

for (int j = 0; j < 4; j++)

for (int i = 0; i < 3; i++)
{
switch(i)
{
case 0:
P.a = adddigit(N.a, j);

if (!flag[atoi(P.a.c_str())])
{
P.step = N.step + 1;
Q.push(P);
flag[atoi(P.a.c_str())] = 1;
if (P.a == b)
{
cout << P.step << endl;;
return;
}
}
break;
case 1:

P.a = minusdigit(N.a, j);
if (!flag[atoi(P.a.c_str())])
{
P.step = N.step + 1;
Q.push(P);
flag[atoi(P.a.c_str())] = 1;
if (P.a == b)
{
cout << P.step << endl;;
return;
}
}

break;
case 2:
if (j != 3)
P.a = changedigit(N.a, j);
if (!flag[atoi(P.a.c_str())])
{
P.step = N.step + 1;
Q.push(P);
flag[atoi(P.a.c_str())] = 1;
if (P.a == b)
{
cout << P.step << endl;
return;
}
}

break;
}
}

}
cout << N.step << endl;

}
string adddigit(string a, int n)
{
if (a
== '9')
a
= '1';
else
a
++;
return a;
}

string minusdigit(string a, int n)
{
if (a
== '1')
a
= '9';
else
a
--;
return a;
}

string changepredigit(string a, int n)
{

string::value_type temp;
temp = a
;
a
= a[n-1];
a[n-1] = temp;
return a;

}
string changedigit(string a, int n)
{

string::value_type temp;
temp = a
;
a
= a[n+1];
a[n+1] = temp;
return a;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: