LeetCode 127. Word Ladder

本文介绍了一种利用广度优先搜索(BFS)算法解决单词转换问题的方法,旨在找到两个单词间最短的转换序列。文章提供了两种实现方案:单向BFS及双向BFS优化版,并附带示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <string>
#include <unordered_set>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

/*
  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:
  1: Return 0 if there is no such transformation sequence.
  2: all words have the same length.
  3: All words contain only lowercase alphabetic characters.
*/

// BFS 
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
  struct wordAndDistance {
    string word;
    int distance;
  };
  queue<wordAndDistance> q;
  wordList.erase(beginWord);
  q.emplace(wordAndDistance{beginWord, 1});
  while(!q.empty()) {
    wordAndDistance f(q.front());
    if(f.word == endWord) return f.distance;

    string str = f.word;
    for(int i = 0; i < str.size(); ++i) {
      for(int j = 0; j < 26; ++j) {
        str[i] = 'a' + j;
        auto it(wordList.find(str));
        if(it != wordList.end()) {
          wordList.erase(it);
          q.emplace(wordAndDistance{str, f.distance + 1});
        }
      }
      str[i] = f.word[i];
    }
    q.pop();
  }
  return -1;
}

int main(void) {
  string beginWord = "hit";
  string endWord = "cog";
  unordered_set<string> wordList{"hot", "dot", "dog", "lot", "log", "cog", "hit"};
  cout << ladderLength(beginWord, endWord, wordList) << endl;
}
 


Further Optimized way: BFS from bi-directional and start from the fewer options' end 

#include "header.h"
using namespace std;

int shortestLength(string start, string end, unordered_set<string>& dict) {
  unordered_set<string> head;
  head.insert(start);
  unordered_set<string> tail;
  tail.insert(end);
  int length = 2;
  while(!head.empty() && !tail.empty()) {
    if(head.size() > tail.size()) swap(head, tail);
    unordered_set<string> next;
    for(auto iter = head.begin(); iter != head.end(); ++iter) {
      string curr = *iter;
      for(int j = 0; j < curr.size(); ++j) {
        char c = curr[j];
        for(char ch = 'a'; ch <= 'z'; ++ch) {
          curr[j] = ch;
          if(tail.find(curr) != tail.end()) return length;
          if(dict.count(curr)) {
            next.insert(curr);
            dict.erase(curr);
          }
        }
        curr[j] = c;
      }
    }
    ++length;
    swap(head, next);
  }
  return 0;
}

int main(void) {
  unordered_set<string> dict{"hot", "dot", "dog", "lot", "log", "hit"};
  cout << shortestLength("hit", "cog", dict) << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值