zoukankan      html  css  js  c++  java
  • Word Ladder I

    问题描述

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

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

    For 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.

    程序

    public class Solution {
        public int ladderLength(String beginWord, String endWord,
    			Set<String> wordDict) {
    		if (beginWord == null || endWord == null || wordDict == null) {
    			return 0;
    		}
    		
    		Queue<String> q = new LinkedList<String>();
    		q.offer(beginWord);
    		int level = 0;
    		boolean flag = false;
    
    		ps: while (true) {
    			int size = q.size();
    			for (int i = 0; i < size; i++) {
    				String s = q.poll();
    				for (int j = 0; j < s.length(); j++) {
    					char[] cc = s.toCharArray();
    					for (int k = 0; k < 26; k++) {
    						char c = (char) ('a' + k);
    						if (c == cc[j]) {
    							continue;
    						}
    						cc[j] = c;
    						String new_s = new String(cc);
    						if (new_s.equals(endWord)) {
    							flag = true;
    							break ps;
    						}
    						if (wordDict.contains(new_s)) {
    							q.offer(new_s);
    							wordDict.remove(new_s);
    						}
    					}
    				}
    			}
    			if (q.isEmpty()) {
    				break;
    			}
    			++level;
    		}
    
    		return flag ? level + 2 : 0;
    	}
    }
    
  • 相关阅读:
    shell脚本积累
    while,shift,until,case
    条件测试命令,if命令,双圆括号,双中括号
    seq命令,tr命令,sort命令,cut命令
    正则,grep命令详解
    Ansible实现批量管理服务器
    实时同步服务知识梳理
    RHEL7破解密码操作步骤
    运维核心基础知识之——MD5sum校验文件
    Linux运维基础提高之RAID卡和磁盘分区
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4737635.html
Copyright © 2011-2022 走看看