[最短路]Open the Lock

Posted lllxq

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[最短路]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.

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.

 

输出

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

 

样例输入

2
1234
2144

1111
9999

样例输出

2
4

 bfs+优先队列求最短路

技术图片
#include <iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;

int st,ed;
int vis[10005];
int tmp[5];
struct Node{
  int val,step;
  bool operator <(const Node b)const{
    return step>b.step;
  }
};
priority_queue<Node> q;

int bfs(){
  while(!q.empty()) q.pop();
  vis[st]=1;q.push(Node{st,0});
  while(!q.empty()){
    Node top=q.top();q.pop();
    int val=top.val,step=top.step;
    if(val==ed) return step;
    tmp[1]=(val/1000)%10,tmp[2]=(val/100)%10;
    tmp[3]=(val/10)%10,tmp[4]=(val/1)%10;
    int cpy;
    for(int i=1;i<=4;i++){
        cpy=tmp[i];
        if(tmp[i]==9) tmp[i]=1;
        else tmp[i]++;
        int now=tmp[1]*1000+tmp[2]*100+tmp[3]*10+tmp[4];
        if(!vis[now]) vis[now]=1,q.push(Node{now,step+1});
        tmp[i]=cpy;
    }
    for(int i=1;i<=4;i++){
        cpy=tmp[i];
        if(tmp[i]==1) tmp[i]=9;
        else tmp[i]--;
        int now=tmp[1]*1000+tmp[2]*100+tmp[3]*10+tmp[4];
        if(!vis[now]) vis[now]=1,q.push(Node{now,step+1});
        tmp[i]=cpy;
    }
    for(int i=1;i<=3;i++){
        swap(tmp[i],tmp[i+1]);
        int now=tmp[1]*1000+tmp[2]*100+tmp[3]*10+tmp[4];
        if(!vis[now]) vis[now]=1,q.push(Node{now,step+1});
        swap(tmp[i],tmp[i+1]);
    }
  }
  return -1;
}

int main()
{
    int t;scanf("%d",&t);
    while(t--){
        memset(vis,0,sizeof(vis));
        scanf("%d%d",&st,&ed);
        int ans=bfs();
        printf("%d
",ans);
    }
    return 0;
}
View Code

 

以上是关于[最短路]Open the Lock的主要内容,如果未能解决你的问题,请参考以下文章

752. Open the Lock

[LeetCode] Open the Lock 开锁

[LC] 752. Open the Lock

[leetcode-753-Open the Lock]

[LC] 752. Open the Lock

[HDU1195]Open the Lock