2021-7-22 Open the Lock
难度 中等
题目 Leetcode:
752.Open the Lock
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.
The lock initially starts at '0000', a string representing the state of the 4 wheels.
You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.
Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
Constraints:
- 1 <= deadends.length <= 500
- deadends[i].length == 4
- target.length == 4
- target will not be in the list deadends.
- target and deadends[i] consist of digits only.
Keyword
slot 狭槽
initially 最初
题目解析
本题大意就是要把0000转到target,每次改变一位,但改变的过程中不能与死亡数字相同、一开始我是头铁用string数组存每次情况,很快啊,直接爆了,然后就转而去用int,我把次数存在每次情况里
比如初始入队10000代表第1次操作把0000放入队列,出队完入队20001代表第二次操作入队0001以此类推,但是这样毫无疑问每次都需要取模运算量还是不小的,其实这题用二进制存的话会很快。
1 queue<int>x; 2 bitset<100005>book; 3 class Solution { 4 public: 5 int ans; 6 bool judge(int temp,int nm[],int length) 7 { 8 int ttemp=temp%10000; 9 for(int i=0;i<length;i++) 10 { 11 if(ttemp==nm[i])return 0; 12 } 13 return 1; 14 } 15 void record(int temp) 16 { 17 book[temp%10000]=1; 18 x.push(temp+10000); 19 } 20 bool bfs(int target,int nm[],int length) 21 { 22 while(!x.empty()) 23 { 24 int a=x.front(); 25 x.pop(); 26 int temp; 27 if(a%10000==target) 28 { 29 ans=a; 30 return 1; 31 } 32 else 33 { 34 for(int i=1;i<=4;i++) 35 { 36 temp=a; 37 int cnt=pow(10,i);//10000 38 int acnt=pow(10,i-1); 39 if((temp % cnt)/acnt!=9) temp+=acnt; 40 else temp-=9*acnt; 41 if((!book[temp%10000])&&judge(temp,nm,length))record(temp); 42 temp=a; 43 if((temp % cnt)/acnt!=0) temp-=acnt; 44 else temp+=9*acnt; 45 if((!book[temp%10000])&&judge(temp,nm,length))record(temp); 46 } 47 } 48 } 49 return 0; 50 } 51 int openLock(vector<string>& deadends, string target) { 52 int nm[502]; 53 stringstream ss; 54 ss<<target; 55 int ttarget; 56 ss>>ttarget; 57 int length=deadends.size(); 58 for(int i=0;i<length;i++) 59 { 60 stringstream ss; 61 ss<<deadends[i]; 62 ss>>nm[i]; 63 } 64 while(!x.empty())x.pop(); 65 x.push(10000); 66 book.reset(); 67 book[0]=1; 68 if(!judge(10000,nm,length))return -1; 69 if(bfs(ttarget,nm,length))return ans/10000-1; 70 else return -1; 71 } 72 };