原题链接在这里: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:

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

Example 2:

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

Example 3:

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

Example 4:

Input: deadends = ["0000"], target = "8888"
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:

 class Solution {
public int openLock(String[] deadends, String target) {
HashSet<String> hs = new HashSet<>(Arrays.asList(deadends));
if(hs.contains("0000") || hs.contains(target)){
return -1;
} LinkedList<Node> que = new LinkedList<>();
HashSet<String> visited = new HashSet<>();
visited.add("0000");
que.add(new Node("0000", 0));
while(!que.isEmpty()){
Node cur = que.poll();
if(cur.s.equals(target)){
return cur.num;
} String s = cur.s;
for(int i = 0; i<s.length(); i++){
char c = s.charAt(i);
String can1 = s.substring(0, i) + (c-'0'+1)%10 + s.substring(i+1);
if(!hs.contains(can1) && !visited.contains(can1)){
visited.add(can1);
que.add(new Node(can1, cur.num+1));
} String can2 = s.substring(0, i) + (c-'0'+10-1)%10 + s.substring(i+1);
if(!hs.contains(can2) && !visited.contains(can2)){
visited.add(can2);
que.add(new Node(can2, cur.num+1));
}
}
} return -1;
}
} class Node{
String s;
int num;
public Node(String s, int num){
this.s = s;
this.num = num;
}
}

Could use bidirectional BFS.

Time Complexity: O(V+E).

Space: O(V).

AC Java:

 class Solution {
public int openLock(String[] deadends, String target) {
HashSet<String> deadSet = new HashSet<>(Arrays.asList(deadends));
if(deadSet.contains("0000") || deadSet.contains(target)){
return -1;
} int level = 0;
HashSet<String> beginSet = new HashSet<>();
HashSet<String> endSet = new HashSet<>();
beginSet.add("0000");
endSet.add(target);
while(!beginSet.isEmpty() && !endSet.isEmpty()){
if(beginSet.size() > endSet.size()){
HashSet<String> temp = beginSet;
beginSet = endSet;
endSet = temp;
} HashSet<String> nextSet = new HashSet<>();
for(String s : beginSet){
if(endSet.contains(s)){
return level;
} for(int i = 0; i<s.length(); i++){
char c = s.charAt(i);
String can1 = s.substring(0, i) + (c-'0'+1)%10 + s.substring(i+1);
String can2 = s.substring(0, i) + (c-'0'+10-1)%10 + s.substring(i+1);
if(!deadSet.contains(can1)){
nextSet.add(can1);
} if(!deadSet.contains(can2)){
nextSet.add(can2);
}
}
} level++;
beginSet = nextSet;
} return -1;
}
}

跟上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. Java学习:迭代器简介

    迭代器 java.util.Iterator接口:迭代器(对集合进行遍历) 有两个常用的方法 boolean hasNext() 如果仍有元素可以迭代,则返回 true. 判断集合中还有没有下一个元素 ...

  2. SQL系列(七)—— 相似(like)

    在看like之前先了解下通配符和搜索模式: 通 配 符 ( wildcard) 用来匹配值的一部分的特殊字符. 搜索模式(search pattern) 由字面值.通配符或两者组合构成的搜索条件. 目 ...

  3. APS.NET MVC + EF (03)---初始MVC

    3.1 MVC简介 MVC(Model-View-Controller,模型—视图—控制器模式)用于表示一种软件架构模式.它把软件系统分为三个基本部分:模型(Model),视图(View)和控制器(C ...

  4. 前端开发常用 JS 方法

    1,获取文件本地url,在上传之前预览 /** * 获取图片嗯滴url,在上传之前预览 * @param file 选择的图片文件 * @returns {*} url */ getFileLocat ...

  5. CSS3 弹性盒布局

    一.伸缩布局 CSS3 在布局方面做了非常大的改进,使得我们对块级元素的布局排列变得十分灵活,适应性非常强,其强大的伸缩性,在响应式开中可以发挥极大的作用. 二.定义 Flexbox 语法格式: di ...

  6. SAP Cloud Platform integration上创建一个最简单的iFlow

    登录SAP CPI控制台,点击这个铅笔图标进入工作区域: 选择一个已经存在的content package: 在这个content package里创建一个新的iFlow: 默认生成的iFlow模型如 ...

  7. SQL-连接查询:left join,right join,inner join,full join之间的区别

    参考: https://www.cnblogs.com/lijingran/p/9001302.html https://www.cnblogs.com/assasion/p/7768931.html ...

  8. NumPy 之 案例(随机漫步)

    import numpy as np The numpy.random module supplements(补充) the built-in Python random with functions ...

  9. The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone 。

    The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. 今天有Mys ...

  10. win10 + Ubuntu18.04 双系统,UEFI+GPT,从win10切换到Ubuntu时黑屏问题

    1.现象: ①win10主系统,从win10重启,立即黑屏,之后会进入Ubuntu(还是黑屏)(为什么会知道进入了Ubuntu:按音量键可以听到Ubuntu音量加减的系统声音,数字锁定和大小写锁定均有 ...