LeetCode 127. 单词接龙 ---BFS模拟

  1. 单词接龙

字典 wordList 中从单词 beginWord 和 endWord 的 转换序列 是一个按下述规格形成的序列:

序列中第一个单词是 beginWord 。
序列中最后一个单词是 endWord 。
每次转换只能改变一个字母。
转换过程中的中间单词必须是字典 wordList 中的单词。

给你两个单词 beginWord 和 endWord 和一个字典 wordList ,找到从 beginWord 到 endWord 的 最短转换序列 中的 单词数目 。如果不存在这样的转换序列,返回 0。

示例 1:

输入:beginWord = “hit”, endWord = “cog”, wordList = [“hot”,“dot”,“dog”,“lot”,“log”,“cog”]
输出:5
解释:一个最短转换序列是 “hit” -> “hot” -> “dot” -> “dog” -> “cog”, 返回它的长度 5。

示例 2:

输入:beginWord = “hit”, endWord = “cog”, wordList = [“hot”,“dot”,“dog”,“lot”,“log”]
输出:0
解释:endWord “cog” 不在字典中,所以无法进行转换。

提示:

1 <= beginWord.length <= 10
endWord.length == beginWord.length
1 <= wordList.length <= 5000
wordList[i].length == beginWord.length
beginWord、endWord 和 wordList[i] 由小写英文字母组成
beginWord != endWord
wordList 中的所有字符串 互不相同

题解

BFS直接模拟。

AC代码

class Solution {
public:
    bool check(string s1,string s2)
    {
        int ans=0;
        for(int i=0;i<s1.length();i++)
        if(s1[i]!=s2[i])
        {
            ans++;
            if(ans>1)return false;
        }
        return true;
    }
    struct Node
    {
        int id,dp;
    };
    vector<int>to[5010];
    bool vis[5010];
    queue<Node>q;
    int bfs(int st,int et)
    {
        memset(vis,0,sizeof(vis));
        Node t;
        t.id=st,t.dp=1;
        q.push(t);
        vis[st]=true;
        while(!q.empty())
        {
            t=q.front();
            q.pop();
            for(int i=0;i<to[t.id].size();i++)
            {
                int v=to[t.id][i];
                if(vis[v])continue;
                if(v==et)return t.dp+1;
                vis[v]=true;
                Node w;
                w.id=v,w.dp=t.dp+1;
                q.push(w);
            }
        }
        return 0;
    }
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        wordList.push_back(beginWord);
        int et=-1;
        for(int i=0;i<wordList.size();i++)
        {
            if(wordList[i]==endWord)
            et=i;
            for(int j=i+1;j<wordList.size();j++)
            {
                if(check(wordList[i],wordList[j]))
                {
                    to[i].push_back(j);
                    to[j].push_back(i);
                }
            }
        }
        if(et==-1)return 0;
        return bfs(wordList.size()-1,et);
    }
};

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值