问题:
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:
The length of deadends will be in the range [1, 500].
target will not be in the list deadends.
Every string in deadends and the string target will be a string of 4 digits from the 10,000 possibilities '0000' to '9999'.
解:
public class Lock {
// Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
// Output: 6
private static final String target = "0202";
private static final String[] deadends = new String[]{"0201","0101","0102","1212","2002"};
// private static final String target = "0009";
// private static final String[] deadends = new String[]{"8888"};
public int openLock(String[] deadends, String target) {
if(deadends==null||deadends.length<1||deadends.length>500){
return -1;
}
for (int i = 0; i < deadends.length; i++) {
String string = deadends[i];
if("0000".equals(string)){
return -1;
}
}
ArrayDeque<String[]> queue=new ArrayDeque<String[]>();
queue.add(new String[]{"0000","0"});
HashSet<String> seen =new HashSet<String>();
seen.add("0000");
// Iterator it=null;
// while((it=queue.iterator()).hasNext()){
// String[]data=(String[]) it.next();
// String current=data[0];
// int count=Integer.valueOf(data[1]);
// it.remove();
while(!queue.isEmpty()){
String[] data=queue.removeFirst();
String current=data[0];
int count=Integer.valueOf(data[1]);
System.out.println("current="+current);
if(current.equals(target)){
System.out.println("queue size="+queue.size()); //5034
return count;
}
count++;
for(int i=0;i<4;i++){
char charTemp=current.charAt(i);
String temp1=current.substring(0,i)+(charTemp=='9'?'0':String.valueOf((charTemp-'0'+1)))+current.substring(i+1);
String temp2=current.substring(0,i)+(charTemp=='0'?'9':String.valueOf(charTemp-'0'-1))+current.substring(i+1);
//注意:下面的写法错误:jdk1.8会导致'9'变成“57”,存在拆箱和装箱的问题。
// String temp1=current.substring(0,i)+(charTemp=='9'?'0':String.valueOf((charTemp-'0'+1)))+current.substring(i+1);
// String temp2=current.substring(0,i)+(charTemp=='0'?'9':String.valueOf(charTemp-'0'-1))+current.substring(i+1);
if(!contains(deadends,temp1)&&!seen.contains(temp1)){
queue.addLast(new String[]{temp1,Integer.toString(count)});
seen.add(temp1);
}
if(!contains(deadends,temp2)&&!seen.contains(temp2)){
queue.addLast(new String[]{temp2,Integer.toString(count)});
seen.add(temp2);
}
}
}
return -1;
}
private boolean contains(String[] deadends, String str) {
if(deadends==null){
return false;
}
for (int i = 0; i < deadends.length; i++) {
if(str.equals(deadends[i])){
return true;
}
}
return false;
}
算法说明:
1.广度遍历,涉及入队和出队的操作。
需要思考:什么时候入队,什么时候出队。
a.死循环遍历队列里的数据,出队(移除队尾),并判断出队的数据是否和目标相等。
b.将每一列的数据,+-,根据条件入队(是否是死锁),是否已经存在过。
2.最小可达数。
重点:将4列,前转和后转各算1次计数。
3.后面思考优化的空间
问题:队列中的数量会很大,如上解法,最终队列的大小为:5034。
另外用了一个hashset去保存之前达到的排列。会占用比较大的空间。
延深的问题:
常见的ASCII码
// ASCII码从0到127,即(2的0次方减1)到(2的7次方减1).
// - 字符’0’对应的ASCII码值是48(转化为int类型);
// - 字符’9’对应的ASCII码值是57 (48+10-1=57);
// - 字符‘A’对应的ASCII码值是65;
// - 字符‘Z’对应的ASCII码值是90(65+26-1=90);
// - 字符‘a’对应的ASCII码值是97;
// - 字符‘z’对应的ASCII码值是122(97+26-1=122);
// - 字符‘NULL(null)’对应的ASCII码值是0,‘NULL(null)’解释为空字符;
// - 字符‘ (space)’对应的ASCII码值是40,‘ (space)’解释为空格;
下面代码行数:1到10行,执行结果分别为:
a1b
a57b
a1b
1.package com.zj.suanfa;
2.
3.public class test {
4. public static void main(String[] args) {
5. char charTemp='0';
6. System.out.println("a"+(charTemp=='9'?'0':String.valueOf(charTemp-'0'+1))+"b");
7. System.out.println("a"+(charTemp=='0'?'9':(charTemp-'0'-1))+"b");
8. System.out.println("a"+(charTemp=='9'?'0':(charTemp-'0'+1))+"b");
9. }
10.}
反编译工具JD-GUI 查看字节码:
public static void main(String[] args)
{
char charTemp = '0';
System.out.println("a" + (charTemp == '9' ? Character.valueOf('0') : String.valueOf(charTemp - '0' + 1)) + "b");
System.out.println("a" + (charTemp == '0' ? 57 : charTemp - '0' - 1) + "b");
System.out.println("a" + (charTemp == '9' ? 48 : charTemp - '0' + 1) + "b");
}
MAC终端执行命令如下:(注:需要进入到test.java所在的目录执行命令)
javac /Users/xx/server/test/src/com/zj/suanfa/test.java
javap -c test
显示结果如下:
public class com.zj.suanfa.test {
public com.zj.suanfa.test();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: bipush 48
2: istore_1
3: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
6: new #3 // class java/lang/StringBuilder
9: dup
10: invokespecial #4 // Method java/lang/StringBuilder."<init>":()V
13: ldc #5 // String a
15: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
18: iload_1
19: bipush 57
21: if_icmpne 32
24: bipush 48
26: invokestatic #7 // Method java/lang/Character.valueOf:(C)Ljava/lang/Character;
29: goto 41
32: iload_1
33: bipush 48
35: isub
36: iconst_1
37: iadd
38: invokestatic #8 // Method java/lang/String.valueOf:(I)Ljava/lang/String;
41: invokevirtual #9 // Method java/lang/StringBuilder.append:(Ljava/lang/Object;)Ljava/lang/StringBuilder;
44: ldc #10 // String b
46: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
49: invokevirtual #11 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
52: invokevirtual #12 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
55: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
58: new #3 // class java/lang/StringBuilder
61: dup
62: invokespecial #4 // Method java/lang/StringBuilder."<init>":()V
65: ldc #5 // String a
67: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
70: iload_1
71: bipush 48
73: if_icmpne 81
76: bipush 57
78: goto 87
81: iload_1
82: bipush 48
84: isub
85: iconst_1
86: isub
87: invokevirtual #13 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
90: ldc #10 // String b
92: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
95: invokevirtual #11 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
98: invokevirtual #12 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
101: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
104: new #3 // class java/lang/StringBuilder
107: dup
108: invokespecial #4 // Method java/lang/StringBuilder."<init>":()V
111: ldc #5 // String a
113: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
116: iload_1
117: bipush 57
119: if_icmpne 127
122: bipush 48
124: goto 133
127: iload_1
128: bipush 48
130: isub
131: iconst_1
132: iadd
133: invokevirtual #13 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
136: ldc #10 // String b
138: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
141: invokevirtual #11 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
144: invokevirtual #12 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
147: return
}
重点关注:goto指令。如:
41: invokevirtual #9 // Method java/lang/StringBuilder.append:(Ljava/lang/Object;)Ljava/lang/StringBuilder;
87: invokevirtual #13 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
133: invokevirtual #13 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
指令说明:
41行指令和另外两个指令不同,所传参数为Ljava/lang/Object;
87和133指令,都为(I) int类型
其他指令:
19: bipush 57 //加载的是字符‘9’
24: bipush 48 //加载的字符是‘a’
分析:java文件在编译的过程中,进行了优化,一般指令都会转成数字。如果字符,就转成对应的ASCII码。特别是:使用a?b:c这种结构的表达式,需要注意,字符类型转换,以及装箱拆箱的过程。
数据结构:
ArrayDeque ,见:https://www.jianshu.com/p/0f10ef73bad3