hdu 1195——Open the Lock(BFS)
来源:互联网 发布:怎样应对大数据时代 编辑:程序博客网 时间:2024/06/05 06:19
题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1195
解题思路:一看本题是求开锁的最少步数,就知道是用bfs了。广搜的基本步骤都是一样,一般是通过队列来求最短路,最优解等等。注意+1、-1和交换三种情况的处理,第一个数字和第四个数字不能交换。学习了一下网上的代码...
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <queue>using namespace std;int vis[10][10][10][10]; //标记int t,final[4],lock;char s1[5],s2[5];struct node{int n[4],step;}key;int bfs(node key){int i;node now,next; //now当前的数字,next下一个状态的数字queue<node>q;q.push(key);while(!q.empty()){now=q.front();q.pop();lock=1; //lock记录锁的状态for(i=0;i<4;i++){if(now.n[i]!=final[i]){lock=0;break;}}if(lock)return now.step;//所有数加1for(i=0;i<4;i++){next=now;if(now.n[i]==9)next.n[i]=1;elsenext.n[i]=now.n[i]+1;if(!vis[next.n[0]][next.n[1]][next.n[2]][next.n[3]]){vis[next.n[0]][next.n[1]][next.n[2]][next.n[3]]=1;next.step=now.step+1;q.push(next);}}//所有数减1for(i=0;i<4;i++){next=now;if(now.n[i]==1)next.n[i]=9;elsenext.n[i]=now.n[i]-1;if(!vis[next.n[0]][next.n[1]][next.n[2]][next.n[3]]){vis[next.n[0]][next.n[1]][next.n[2]][next.n[3]]=1;next.step=now.step+1;q.push(next);}}//与相邻的交换,4个数只能交换三次for(i=0;i<3;i++){next=now;next.n[i]=now.n[i+1];next.n[i+1]=now.n[i];if(!vis[next.n[0]][next.n[1]][next.n[2]][next.n[3]]){vis[next.n[0]][next.n[1]][next.n[2]][next.n[3]]=1;next.step=now.step+1;q.push(next);}}}return -1;}int main(){int i;scanf("%d",&t);getchar();while(t--){scanf("%s",s1);scanf("%s",s2);for(i=0;i<4;i++){key.n[i]=s1[i]-'0';final[i]=s2[i]-'0';}memset(vis,0,sizeof(vis));key.step=0;printf("%d\n",bfs(key));}return 0;}
- hdu 1195——Open the Lock(BFS)
- HDU——1195Open 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)
- 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)
- C# 跨平台
- 【3DSmax】3DSmax9基础建模教程—读书笔记2(第二课)
- FIFO 有名管道
- Responding to Touch Events 响应触摸事件
- Objective-C 访问权限 public private protect
- hdu 1195——Open the Lock(BFS)
- Using Network Service Discovery 使用网络服务搜索
- 《游戏脚本的设计与开发》-目录&序
- VTP协议及其配置
- Connecting with Wi-Fi Direct 与Wi-Fi直接连接
- Android&IOS开源项目整理(记得就更新)
- Using Wi-Fi Direct for Service Discovery 直接使用Wi-Fi服务发现
- CF:43A. Football
- Setting Up the Loader 设置装载机