首页 > 代码库 > HDU-1195-Open the Lock(BFS)
HDU-1195-Open the Lock(BFS)
Problem Description
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.
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.
Input
The input file begins with an integer T, indicating the number of test cases.
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.
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
Author
YE, Kai
Source
Zhejiang University Local Contest 2005
思路:又是一道水题。
#include <stdio.h> #include <string.h> #include <cstdlib> struct{ char num[5]; int step; }que[1000000],t; int p[4]={1,10,100,1000}; bool vis[10000]; int main() { int T,i,j,len,val,temp; char des[5]; scanf("%d",&T); while(T--) { scanf("%s%s",que[0].num,des); int top=0,bottom=1; que[0].step=0; memset(vis,0,sizeof vis); while(top<bottom) { t=que[top]; if(strcmp(t.num,des)==0) { printf("%d\n",t.step); break; } t.step++; for(i=0;i<4;i++) { if(t.num[i]=='9') t.num[i]='1'; else t.num[i]++; val=0; for(j=0;j<4;j++) val=val*10+t.num[j]-'0'; if(!vis[val]) { vis[val]=1; que[bottom++]=t; } strcpy(t.num,que[top].num); if(t.num[i]=='1') t.num[i]='9'; else t.num[i]--; val=0; for(j=0;j<4;j++) val=val*10+t.num[j]-'0'; if(!vis[val]) { vis[val]=1; que[bottom++]=t; } strcpy(t.num,que[top].num); } for(i=0;i<3;i++) { temp=t.num[i]; t.num[i]=t.num[i+1]; t.num[i+1]=temp; val=0; for(j=0;j<4;j++) val=val*10+t.num[j]-'0'; if(!vis[val]) { vis[val]=1; que[bottom++]=t; } temp=t.num[i]; t.num[i]=t.num[i+1]; t.num[i+1]=temp; } top++; } } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。