zoukankan      html  css  js  c++  java
  • Word Ladder(LintCode)

    Word Ladder

    Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

    1. Only one letter can be changed at a time
    2. Each intermediate word must exist in the dictionary
    Example

    Given:
    start = "hit"
    end = "cog"
    dict = ["hot","dot","dog","lot","log"]

    As one shortest transformation is"hit" -> "hot" -> "dot" -> "dog" -> "cog",
    return its length 5.

    Note
    • Return 0 if there is no such transformation sequence.
    • All words have the same length.
    • All words contain only lowercase alphabetic characters.

    用BFS做,字符串只相差一个字符的就当作有边。

     1 public class Solution {
     2     /**
     3       * @param start, a string
     4       * @param end, a string
     5       * @param dict, a set of string
     6       * @return an integer
     7       */
     8     public int ladderLength(String start, String end, Set<String> dict) {
     9         Queue q = new LinkedList();
    10         dict.add(end);
    11         int reslut = 0;
    12         
    13         //转成List方便标记,其实也可以将搜索过的String从Set中移除
    14         List<String> list = new ArrayList<String>(dict);
    15         int[] flag = new int[list.size()];
    16         q.add(start);
    17         int n = 1;
    18         int x = 0;
    19         while(q.size() > 0) {
    20             String y = (String)q.remove();
    21             n--;
    22             for (int i = 0;i<list.size() ;i++ ) {
    23                 if(end.equals(y)) return reslut+1;
    24                 if (judge(list.get(i),y) == 1 && flag[i] == 0) {
    25                     x++;
    26                     q.add(list.get(i));
    27                     flag[i] = 1;
    28                 }
    29             }
    30             if (n == 0) {
    31                 n = x;
    32                 x = 0;
    33                 reslut++;
    34             }
    35         }
    36 
    37         return 0;
    38     }
    39 
    40     public int judge(String a,String b) {
    41         int num = 0;
    42         char[] acs = a.toCharArray();
    43         char[] bcs = b.toCharArray();
    44         for (int i = 0;i<acs.length ;i++ ) {
    45             if(acs[i] != bcs[i]) num++;
    46         }
    47         return num;
    48     }
    49 }
  • 相关阅读:
    32位和64位系统区别及int字节数
    c语言指针占几个字节
    可重入和不可重入
    C中的volatile用法
    让你分分钟读懂CPU架构及芯片厂商
    手机CPU知识扫盲:谈谈手机CPU架构与原理 (全
    IO端口、IO内存、IO空间、内存空间的含义和联系
    IO端口和IO内存的区别及分别使用的函数接口
    linux终端下 编译c语言程序
    git各种撤销操作
  • 原文地址:https://www.cnblogs.com/FJH1994/p/5041418.html
Copyright © 2011-2022 走看看