BFS--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:
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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,980评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,178评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,868评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,498评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,492评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,521评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,910评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,569评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,793评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,559评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,639评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,342评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,931评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,904评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,144评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,833评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,350评论 2 342

推荐阅读更多精彩内容