127.Word Ladder

昨天晚上在LeetCode随便选了一道题写会儿代码,选中了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.
刚开始看到这道题时想了一会儿,第一想法是创建一个二维数组,数组中的横行和纵行分别对应所有的单词,将横行和纵行中长度相同并且只有一位不同的两个单词对应的位置设置为1,其他情况下设置为0.接着,看到二维数组想到图中的邻接矩阵,想到可以用图轮方面的知识解答该题,但是具体用什么方法没有思路。于是,上网查了一下,才知道可以使用广度优先搜索来做,一下子想起来在《数据结构与算法分析:C语言描述》中,在关于图的那一章中讲到单点最短路径的时候,曾经讲过在边没有权值的时候,可以使用广度优先遍历来求解最短路径问题。

代码如下:

#include<iostream>
#include<string>
#include<queue>
#include<unordered_set>
#include<map>

using namespace std;

class Solution {
public:
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
      queue<string> que;
      map<string, int> map;

      if( beginWord == "" || endWord == "" || wordList.empty() )
        return 0;
      if( beginWord == endWord )
        return 1;
      que.push( beginWord );
      map.insert( pair<string, int>( beginWord, 1) );

      while( !que.empty() )
      {
        string currentWord = que.front();
        que.pop();
        int currentLength = map[ currentWord ];
        for( int index = 0; index < currentWord.length(); index++ )
        {
          for( char ch = 'a'; ch <= 'z'; ch++ )
          {
            string temp = currentWord;
            //判断是否重复
            if( ch == temp[ index ])
              continue;
            temp[ index ] = ch;
            if( temp == endWord )
              return currentLength+1;
              //判断是否重复
            if( !map.count( temp ) && wordList.count( temp ) )
            {
              que.push( temp );
              map.insert(pair<string, int>(temp, currentLength+1) );
            }
          }
        }
      }
      return 0;
    }
};

由于该程序中使用了unordered_set类,所以编译的时候采用如下命令进行:

g++ -std=c++11 -o q127 q127.cp


这是我第二次提交的程序,在第一次提交的程序中,由于在加入到map中和修改字母的时候没有判断重复而超时运行,所以在书写广度优先搜索的时候判断是否重复是非常重要的。

有关广度优先遍历的详细总结可以看此链接:http://www.acmerblog.com/leetcode-bfs-6431.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值