原题链接在这里:https://leetcode.com/problems/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.

Example 1:

  1. Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
  2. Output: 6
  3. Explanation:
  4. A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".
  5. Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid,
  6. because the wheels of the lock become stuck after the display becomes the dead end "0102".

Example 2:

  1. Input: deadends = ["8888"], target = "0009"
  2. Output: 1
  3. Explanation:
  4. We can turn the last wheel in reverse to move from "0000" -> "0009".

Example 3:

  1. Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"
  2. Output: -1
  3. Explanation:
  4. We can't reach the target without getting stuck.

Example 4:

  1. Input: deadends = ["0000"], target = "8888"
  2. Output: -1

Note:

  1. The length of deadends will be in the range [1, 500].
  2. target will not be in the list deadends.
  3. Every string in deadends and the string target will be a string of 4 digits from the 10,000 possibilities '0000' to '9999'.

题解:

If the deadends include begin or target string, then it could never reach target, return -1.

Otherwise, use BFS to iterate from "0000".

Every time, we poll and get the current. For each char in current, plus or minus 1, have the new candidate, if the caidiate is not visited or not in the deadend, add it to the queue.

Time Complexity: O(V+E). V is node count. E is edge count.

Space: O(V).

AC Java:

  1. class Solution {
  2. public int openLock(String[] deadends, String target) {
  3. HashSet<String> hs = new HashSet<>(Arrays.asList(deadends));
  4. if(hs.contains("0000") || hs.contains(target)){
  5. return -1;
  6. }
  7.  
  8. LinkedList<Node> que = new LinkedList<>();
  9. HashSet<String> visited = new HashSet<>();
  10. visited.add("0000");
  11. que.add(new Node("0000", 0));
  12. while(!que.isEmpty()){
  13. Node cur = que.poll();
  14. if(cur.s.equals(target)){
  15. return cur.num;
  16. }
  17.  
  18. String s = cur.s;
  19. for(int i = 0; i<s.length(); i++){
  20. char c = s.charAt(i);
  21. String can1 = s.substring(0, i) + (c-'0'+1)%10 + s.substring(i+1);
  22. if(!hs.contains(can1) && !visited.contains(can1)){
  23. visited.add(can1);
  24. que.add(new Node(can1, cur.num+1));
  25. }
  26.  
  27. String can2 = s.substring(0, i) + (c-'0'+10-1)%10 + s.substring(i+1);
  28. if(!hs.contains(can2) && !visited.contains(can2)){
  29. visited.add(can2);
  30. que.add(new Node(can2, cur.num+1));
  31. }
  32. }
  33. }
  34.  
  35. return -1;
  36. }
  37. }
  38.  
  39. class Node{
  40. String s;
  41. int num;
  42. public Node(String s, int num){
  43. this.s = s;
  44. this.num = num;
  45. }
  46. }

Could use bidirectional BFS.

Time Complexity: O(V+E).

Space: O(V).

AC Java:

  1. class Solution {
  2. public int openLock(String[] deadends, String target) {
  3. HashSet<String> deadSet = new HashSet<>(Arrays.asList(deadends));
  4. if(deadSet.contains("0000") || deadSet.contains(target)){
  5. return -1;
  6. }
  7.  
  8. int level = 0;
  9. HashSet<String> beginSet = new HashSet<>();
  10. HashSet<String> endSet = new HashSet<>();
  11. beginSet.add("0000");
  12. endSet.add(target);
  13. while(!beginSet.isEmpty() && !endSet.isEmpty()){
  14. if(beginSet.size() > endSet.size()){
  15. HashSet<String> temp = beginSet;
  16. beginSet = endSet;
  17. endSet = temp;
  18. }
  19.  
  20. HashSet<String> nextSet = new HashSet<>();
  21. for(String s : beginSet){
  22. if(endSet.contains(s)){
  23. return level;
  24. }
  25.  
  26. for(int i = 0; i<s.length(); i++){
  27. char c = s.charAt(i);
  28. String can1 = s.substring(0, i) + (c-'0'+1)%10 + s.substring(i+1);
  29. String can2 = s.substring(0, i) + (c-'0'+10-1)%10 + s.substring(i+1);
  30. if(!deadSet.contains(can1)){
  31. nextSet.add(can1);
  32. }
  33.  
  34. if(!deadSet.contains(can2)){
  35. nextSet.add(can2);
  36. }
  37. }
  38. }
  39.  
  40. level++;
  41. beginSet = nextSet;
  42. }
  43.  
  44. return -1;
  45. }
  46. }

跟上Word Ladder II.

LeetCode 752. Open the Lock的更多相关文章

  1. [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', ...

  2. 【LeetCode】752. Open the Lock 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  3. LeetCode 752:打开转盘锁 Open the Lock

    题目: 你有一个带有四个圆形拨轮的转盘锁.每个拨轮都有10个数字: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' .每个拨轮可以自由旋转:例如把 ' ...

  4. [LeetCode] 0752. Open the Lock 打开转盘锁

    题目 You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', ' ...

  5. LC 752 Open the Lock

    由于这个问题,涉及了很多知识,例如数据结构里面的哈希表,c++中的迭代器,因此,需要对于每一个疑惑逐一击破. 问题描述 You have a lock in front of you with 4 c ...

  6. Java实现 LeetCode 752 打开转盘锁(暴力)

    752. 打开转盘锁 你有一个带有四个圆形拨轮的转盘锁.每个拨轮都有10个数字: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' .每个拨轮可以自由旋 ...

  7. Leetcode: Find Permutation(Unsolve lock problem)

    By now, you are given a secret signature consisting of character 'D' and 'I'. 'D' represents a decre ...

  8. leetcode 752. 打开转盘锁

    地址 https://leetcode-cn.com/problems/open-the-lock/ 你有一个带有四个圆形拨轮的转盘锁.每个拨轮都有10个数字: '0', '1', '2', '3', ...

  9. LeetCode All in One题解汇总(持续更新中...)

    突然很想刷刷题,LeetCode是一个不错的选择,忽略了输入输出,更好的突出了算法,省去了不少时间. dalao们发现了任何错误,或是代码无法通过,或是有更好的解法,或是有任何疑问和建议的话,可以在对 ...

随机推荐

  1. golang输出双精度浮点例子(Printf)

    1 package main import "fmt" func main() { var sum int = 17 var count int = 5 var mean floa ...

  2. Matlab的solve()函数的使用方法

    Matlab的solve()函数的使用方法 1.首先是对方程的求解 不废话直接上例子 syms x: eq=x^2+2*x+1; s=solve(eq,x); 结果如下 完美的算出了方程的解 现在对上 ...

  3. Java学习:运算符的使用与注意事项

    运算符的使用与注意事项 四则运算当中的加号“+”有常见的三种用法: 对于数值来,那就是加法. 对于字符char类型来说,在计算之前,char会被提升成为int,然后再计算.char类型字符,和int类 ...

  4. Linux中历史命令

    历史命令,即之前登录session会话中的在命令行键入的命令. 在Linux中可以有两种方式查询历史命令 history命令 当前用户目录中的隐藏文件.bash_history 一.history 作 ...

  5. C# SQl通过对视图数据二次查询,统计数据

    问题描述: 原数据---------需要在原视图数据中,统计出每个Device_Num设备号下面的交易的总额和分别统计出微信支付宝的交易总额. 解决:从上图数据没办法使用直接查询出要求的数据. .1. ...

  6. 第三章 Maven构建 Java Spring Boot Web项目

    3.1   认识Srping Boot Spring Boot是一个框架,是一种全新的编程规范,它的产生简化了对框架的使用,简化了Spring众多的框架中大量的繁琐的配置文件,所以说Spring Bo ...

  7. ios、安卓前端兼容性

    1.日期兼容性 解决方法(请看我上一篇文章)安卓.ios时间转换成时间戳的形式 2.input框聚焦,ios出现outline或者阴影,安卓显示正常 解决方法 input:focus{outline: ...

  8. 工具sublime安装

    默认安装后是英文版 view-show console 安装packagecontrol https://packagecontrol.io/installation ctrl+`打开控制台,输入代码 ...

  9. Django:RestFramework之-------路由

    11.路由 路由设置: url(r'^(?P<version>[v1|v2]+)/vview\.(?P<format>\w+)$', views.VView.as_view({ ...

  10. Java JDBC事务

    JDBC默认是自动提交,事务是关闭的,statement|preparedStatement.executeUpdate()或excute()执行增删改,执行一次就提交一次(自动同步到数据库). JD ...