• leetcode126 Word Ladder II


    思路:

    宽搜过程中分层记录路径,递归还原。
    实现:

     1 class Solution 
     2 {
     3 public:
     4     void getPath(string now, string beginWord, string endWord, vector<string>& buf, unordered_map<string, unordered_set<string>>& par, vector<vector<string>>& ret)
     5     {
     6         if (now == beginWord)
     7         {
     8             vector<string> tmp(1, endWord);
     9             for (auto it : buf) tmp.push_back(it);
    10             ret.push_back(tmp);
    11             reverse(ret.back().begin(), ret.back().end());
    12             return;
    13         }
    14         for (auto it : par[now])
    15         {
    16             buf.push_back(it);
    17             getPath(it, beginWord, endWord, buf, par, ret);
    18             buf.pop_back();
    19         }
    20     }
    21     vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) 
    22     {
    23         unordered_set<string> tmp;
    24         for (auto it : wordList) tmp.insert(it);
    25         unordered_map<string, unordered_set<string>> par;
    26         unordered_set<string> q;
    27         q.insert(beginWord);
    28         bool flg = false;
    29         while (!q.empty())
    30         {
    31             unordered_set<string> next;
    32             for (auto it : q)
    33             {
    34                  for (int i = 0; i < it.length(); i++)
    35                 {
    36                     for (char c = 'a'; c <= 'z'; c++)
    37                     {
    38                         string buf = it;
    39                         if (buf[i] == c) continue;
    40                         buf[i] = c;
    41                         if (!tmp.count(buf)) continue;
    42                         if (!q.count(buf)) 
    43                         {
    44                             next.insert(buf);
    45                             par[buf].insert(it);
    46                         }
    47                         if (buf == endWord) flg = true;
    48                     }    
    49                 } 
    50             }
    51             for (auto it : q) { tmp.erase(it); }
    52             q = next;
    53             if (flg) break;
    54         }
    55         vector<vector<string>> ret;
    56         if (flg) 
    57         {
    58             vector<string> buf;
    59             getPath(endWord, beginWord, endWord, buf, par, ret);
    60         }
    61         return ret;
    62     }
    63 };
  • 相关阅读:
    axublogcms1.1.0 Getshell
    易酷 cms2.5 本地文件包含漏洞 getshell
    通过 phpmyadmin getshell
    python 简单图像识别--验证码
    Linux 入侵检测小结
    beef + msf 实现内网渗透
    phpwind v9存在命令执行漏洞(登陆后台)
    缓冲区溢出实践
    《Metasploit魔鬼训练营》第四章(下)
    《Metasploit魔鬼训练营》第四章(上)
  • 原文地址:https://www.cnblogs.com/wangyiming/p/7518509.html
Copyright © 2020-2023  润新知