hdu 1195 Open the Lock bfs
来源:互联网 发布:小黑屋写作软件app 编辑:程序博客网 时间:2024/04/27 18:29
题意:有一个四位数字的字符串,要求将初始数字串改变成目标数字串,允许的操作有两种:
1、将每一位加1或减1操作,1减1操作变成9,9加1操作变成1;
2、交换相邻的两个字符;
每一种操作为一步,求最少要用多少步才能完成从初始状态到目标状态。
注意:首个字符和最后一个字符不算相邻。
思路:将上面两步分解成四个步骤操作,加1,减1,向左交换,向右交换。用bfs搜索每一种操作状态,找到目标状态就把这次找到目标状态所花的步骤和已经有的最少步骤作比较,这次所用步骤少就将值赋给最少步骤。
最小步骤用steps 保存。
数据结构
struct Q
{
int x [4];// 每一位的数字
int steps;//当前状态已经花费的时间
}
bool vis[10000];//存储已经访问过的每一种状态,如果已经访问过此种状态就不在访问了。
代码:
#include<iostream>#include<queue>#include<cstdio>using namespace std;int s1,s2,s3,s4;int e1,e2,e3,e4;int steps;bool vis[10000];struct Q{ int x[4]; int steps;};void bfs(){ queue<Q>q; Q temp,now; int i,j; int x[4]; int bit[4]={1000,100,10,1}; while(!q.empty())q.pop(); temp.x[0]=s1; temp.x[1]=s2; temp.x[2]=s3; temp.x[3]=s4; temp.steps=0; q.push(temp); steps=0xfffffff; memset(vis,0,sizeof(vis)); vis[s1*1000+s2*100+s3*10+s4]=1; while(!q.empty()) { now=q.front(); q.pop(); if(now.x[0]==e1&&now.x[1]==e2&&now.x[2]==e3&&now.x[3]==e4) { if(steps>now.steps) { steps=now.steps; } } for(i=0;i<4;i++) { for(j=0;j<4;j++) { x[0]=now.x[0];x[1]=now.x[1]; x[2]=now.x[2];x[3]=now.x[3]; temp=now; if(j==0) { x[i]++; if(x[i]>9)x[i]=1; } else if(j==1) { x[i]--; if(x[i]<1)x[i]=9; } else if(j==2) { if(i<=0)continue; int t=x[i]; x[i]=x[i-1]; x[i-1]=t; } else { if(i>=3)continue; int t=x[i]; x[i]=x[i+1]; x[i+1]=t; } //printf("%d %d %d %d\n",x[0],x[1],x[2],x[3]); if(vis[x[0]*bit[0]+x[1]*bit[1]+x[2]*bit[2]+x[3]*bit[3]])continue; vis[x[0]*bit[0]+x[1]*bit[1]+x[2]*bit[2]+x[3]*bit[3]]=1; temp.x[0]=x[0];temp.x[1]=x[1];temp.x[2]=x[2];temp.x[3]=x[3]; temp.steps++; q.push(temp); } } } return;}int main(){ int t; char str[5]; scanf("%d",&t); while(t--) { scanf("%s",str); s1=str[0]-'0'; s2=str[1]-'0'; s3=str[2]-'0'; s4=str[3]-'0'; scanf("%s",str); e1=str[0]-'0'; e2=str[1]-'0'; e3=str[2]-'0'; e4=str[3]-'0'; bfs(); printf("%d\n",steps); } return 0;}
- hdu 1195 Open the Lock bfs
- HDU 1195 Open the Lock BFS
- HDU 1195 Open the lock( BFS)
- hdu-1195--Open the Lock(BFS)
- hdu 1195 Open the Lock (bfs)
- Hdu 1195 Open the Lock [Bfs]
- HDU 1195 Open the Lock (双向BFS)
- HDU-1195-Open the Lock(BFS)
- HDU 1195 Open the Lock BFS
- hdu 1195 Open the Lock (BFS)
- HDU 1195 Open the Lock(双向BFS)
- hdu 1195 Open the Lock(基础bfs)
- 双向BFS-->hdu 1195 Open the Lock
- 【HDU 1195】Open the Lock(BFS)
- hdu 1195 Open the Lock(BFS)
- HDU 1195 Problem:OPEN THE LOCK (bfs)
- HDU--1195--bfs--Open the Lock
- HDU 1195Open the Lock(bfs)
- 【HDU 1864】 最大报销额 DP+剪枝+非递归dfs
- 对一名电子信息工程专业应届毕业生的建议【转自没毛菜鸟要成长的一篇博文】
- 今天遇到的对List,ArrayList的remove方法的一个小问题
- struct dirent
- IQ Test for Top500 Enterprise Cooperation
- hdu 1195 Open the Lock bfs
- Java基础面试遇到问题(一)
- 新闻发布系统中的代码记录1
- Android音量调节的实现(RingtoneManager和RingerVolumePreference)
- 实现Lua的双向队列
- Asp.Net 网站优化系列 数据库优化 分字诀上 分库
- sug176 Flow construction (有上下界最小流)
- Lua代码编写注意点
- 恢复chrome书签