zoukankan      html  css  js  c++  java
  • [LeetCode]Word Ladder

    Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

    1. Only one letter can be changed at a time
    2. Each intermediate word must exist in the dictionary

    For example,

    Given:
    start = "hit"
    end = "cog"
    dict = ["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.

    思考:BFS。

    class Solution {
    public:
    	int ladderLength(string start, string end, unordered_set<string> &dict) {
    		queue<pair<string,int>> q;
    		unordered_set<string> visited;
    		q.push(make_pair(start, 1));
    		visited.insert(start);
    		while (!q.empty())
    		{
    			string curStr = q.front().first;
    			int curStep = q.front().second;
    			q.pop();
    			for (int i = 0; i < curStr.size(); ++i)
    			{
    				string tmp = curStr;
    				for (int j = 0; j < 26; ++j)
    				{
    					tmp[i] = j+'a';
    					if(tmp == end)
    						return curStep+1;
    					if(visited.find(tmp) == visited.end() && dict.find(tmp) != dict.end())
    					{
    						q.push(make_pair(tmp, curStep+1));
    						visited.insert(tmp);
    					}
    				}
    			}
    		}
    		return 0;
    	}
    };
    

      

  • 相关阅读:
    P3180 [HAOI2016]地图
    P2787 语文1(chin1)- 理理思维
    P2221 [HAOI2012]高速公路
    P4137 Rmq Problem / mex
    P3746 [六省联考2017]组合数问题
    P2461 [SDOI2008]递归数列
    P3715 [BJOI2017]魔法咒语
    P3195 [HNOI2008]玩具装箱TOY
    Linux下的strerror是否线程安全?
    bash/shell的字符串trim实现
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3598384.html
Copyright © 2011-2022 走看看