word ladder
Posted yunyouhua
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了word ladder相关的知识,希望对你有一定的参考价值。
超时
public class Solution { public int ladderLength(String beginWord, String endWord, List<String> wordList) { //You may assume beginWord and endWord are non-empty and are not the same. if (wordList == null) { return 0; } int length = 2; Queue<String> queue = new LinkedList<>(); Set<String> hash = new HashSet<>(); queue.add(beginWord); hash.add(beginWord); boolean find = false; while (!queue.isEmpty()) { int size = queue.size(); //System.out.println("length" + length); for (int k = 0; k < size; k++) { String node = queue.poll(); //System.out.println("一层" + node); if (node.equals(endWord)) { find = true; return ++length; } for (int i = 0; i < wordList.size(); i++) { int count = 0; String next = wordList.get(i); if (!hash.contains(next)) { //System.out.print("next"); //System.out.println(next); for (int j = 0; j < node.length(); j++) { if (! (node.substring(j, j + 1).equals(next.substring(j, j + 1)))) { count++; } } if (count == 1) { if (next.equals(endWord)) { return length; } queue.add(next); hash.add(next); //System.out.print("add"); //System.out.println(next); } } } } length++; } return 0; } }
以上是关于word ladder的主要内容,如果未能解决你的问题,请参考以下文章