• leetcode@ [127] Word Ladder (BFS / Graph)


    https://leetcode.com/problems/word-ladder/

    Given two words (beginWord and endWord), and a dictionary's word list, 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 word list

    For example,

    Given:
    beginWord = "hit"
    endWord = "cog"
    wordList = ["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.
    class node {
        public:
            string word;
            int lv;
            node(string s, int v): word(s), lv(v) {}
    };
    
    class Solution {
    public:
        
        int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
            int n = wordList.size();
            
            if(!n)  return 0;
            bool flag = false;
            if(wordList.find(endWord) != wordList.end())  flag = true;
            wordList.insert(endWord);
            
            queue<node> st;
            st.push(node(beginWord, 0));
            
            while(!st.empty()) {
                node top = st.front();
                st.pop();
                int cur_lv = top.lv; 
                string cur_word = top.word;
                
                if(cur_word.compare(endWord) == 0)  return flag? cur_lv+1: cur_lv;
                unordered_set<string>::iterator p = wordList.begin();
                
                for(int i=0; i<cur_word.length(); ++i) {
                    for(char c = 'a'; c <= 'z'; ++c) {
                        char tmp = cur_word[i];
                        if(cur_word[i] != c)  cur_word[i] = c;
                        if(wordList.find(cur_word) != wordList.end()) {
                            st.push(node(cur_word, cur_lv+1));
                            wordList.erase(wordList.find(cur_word));
                        }
                        cur_word[i] = tmp;
                    }
                }
            }
            
            return 0;
        }
    };
  • 相关阅读:
    http调用接口,并解析返回的xml数据,显示在jsp页面上
    项目与tomcat
    项目依赖和部署
    数据库上操作实例 找到要操作的表---筛选---选中要操作的字段---输入
    端口占用问题
    快捷键
    获取页面上的数据
    布尔类型
    EL表达式
    mac oxs 上查看进程监听的端口号 lsof
  • 原文地址:https://www.cnblogs.com/fu11211129/p/5278129.html
Copyright © 2020-2023  润新知