HDU1195(BFS)

Open the Lock

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 2677    Accepted Submission(s): 1178


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.
 

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.
 

Output
For each test case, print the minimal steps in one line.
 

Sample Input
   
   
   
   
2 1234 2144 1111 9999
 

Sample Output
   
   
   
   
2 4
 


//BFS,总共才10*10*10*10个状态,故不会超时!

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
char str1[10];
char str2[10];
struct node 
{
  char str[6];
 int step;
};
bool visited[10][10][10][10];

int bfs()
{
 int i;
 queue<node>qq;
 memset(visited,0,sizeof(visited));
 node a;
 strcpy(a.str,str1);
// a.str=str1;
 a.step=0;
 qq.push(a);
 while(!qq.empty())
 {
  a=qq.front();
  qq.pop();
  for(i=0;i<4;i++)
  {
   if(a.str[i]==str2[i])
    continue;
   else break;
  }
  if(i>=4)
   return a.step;
  node b;
  for(i=0;i<4;i++)
  {
   strcpy(b.str,a.str);
   b.step=a.step+1;
   b.str[i]=a.str[i]+1;
   if(b.str[i]-'0'==10)
    b.str[i]='1';
   if(!visited[b.str[0]-'0'][b.str[1]-'0'][b.str[2]-'0'][b.str[3]-'0'])
   {
    visited[b.str[0]-'0'][b.str[1]-'0'][b.str[2]-'0'][b.str[3]-'0']=true;
    qq.push(b);
   }
  }

  for(i=0;i<4;i++)
  {
   strcpy(b.str,a.str);
   b.step=a.step+1;
   b.str[i]=a.str[i]-1;
   if(b.str[i]-'0'==0)
    b.str[i]='9';
   if(!visited[b.str[0]-'0'][b.str[1]-'0'][b.str[2]-'0'][b.str[3]-'0'])
   {
    visited[b.str[0]-'0'][b.str[1]-'0'][b.str[2]-'0'][b.str[3]-'0']=true;
    qq.push(b);
   }
  }

  for(i=0;i<3;i++)
  {
   b.step=a.step+1;
   strcpy(b.str,a.str);
   char ch=b.str[i];
   b.str[i]=b.str[i+1];
   b.str[i+1]=ch;
   if(!visited[b.str[0]-'0'][b.str[1]-'0'][b.str[2]-'0'][b.str[3]-'0'])
   {
    visited[b.str[0]-'0'][b.str[1]-'0'][b.str[2]-'0'][b.str[3]-'0']=true;
    qq.push(b);
   }
  }
 }
}

int main()
{
 int t;
 cin>>t;
 while(t--)
 {
  scanf("%s",str1);
  scanf("%s",str2);
  cout<<bfs()<<endl;
 }
 return 0;
}


 


 

你可能感兴趣的:(图论,bfs)