- 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
BFS搜索研讨
BFS搜索 open the lock Now an emergent task for you is to open a password lock. The password is consisted of four digits. Each digit is numbered from 1 to 9. Each time, you can add or minus 1 to any digit. When add 1 to 9, the digit will change to be 1 and when minus 1 to 1, the digit will change to be 9. You can also exchange the digit with its neighbor. Each action will take one step. Now your task is to use minimal steps to open the lock. Note: The leftmost digit is not the neighbor of the rightmost digit. The input file begins with an integer T, indicating the number of test cases. input: Each test case begins with a four digit N, indicating the initial state of the password lock. Then followed a line with anotther four dight M, indicating the password which can open the lock. There is one blank line after each test case. output: For each test case, print the minimal steps in one line. sample input: 2 1234 2144 1111 9999 sample output: 2 4 source:/showproblem.php?pid=1195 分析:题目要求最短路径的长度,很显然可以采用BFS来解决。对应的搜索树是一棵k叉树(k为11)。随着层数的递增,需要搜索的节点呈爆炸式增长。但是节点最多其实只有9999个,所以在搜索树中必然存在大量的重复节点。可以采用标记数组进行判重,本题可以很快出解。 bool vis[MAXN]; int bitv[4]={1000,100,10,1}; char str1[5],str2[5]; int s,t; using namespace std; struct node { int num,cnt; node(int a,int b) { num=a,cnt=b; } }; void swp(int num,int pos1,int pos2)//交换num中pos1和pos2的值。 { int t1=num/bitv[pos1]%10,t2=num/bitv[pos2]%10; int d=t1-t2; num-=d*bitv[pos1]; num+=d*bitv[pos2]; } void bfs() { queuenode q; q.push(node(s,0)); vis[s]=1; int tmp=0,bt=0; while(!q.empty()) { int flag=1,step=q.front().cnt; for(int j=0;j2;j++)//增大或减小 { flag=-1*flag; for(int i=0;i4;i++) { tmp=q.front().num; bt=tmp/bitv[i]%10; tmp-=bt*bitv[i]; bt=(bt+flag+8)%9+1; //根据flag的值,修改第i位的值为bt。 tmp+=bitv[i]*bt; if(tmp==t) { printf(%d\n,step+1); return;
文档评论(0)