zoukankan      html  css  js  c++  java
  • LeetCode OJ

    题目:

    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.

    Note:

    • All words have the same length.
    • All words contain only lowercase alphabetic characters.

    解题思路:

      广度优先搜索。另外设置一个标识位来避免死循环。

    代码:

    class Solution {
    public:
        int ladderLength(string start, string end, unordered_set<string> &dict) {
            typedef pair<string, int> node;
            unordered_set<string> visited; //标识位,避免死循环
            queue<node> q;
            q.push(make_pair(start, 1));
            while (!q.empty()) {
                node cur_node = q.front();
                q.pop();
    
                if (cur_node.first == end) return cur_node.second;
    
                for (int i = 0; i < cur_node.first.size(); i++) {
                    string tmp = cur_node.first;
                    for (char j = 'a'; j <= 'z'; j++) {
                        tmp[i] = j; //change one character
                        if (tmp == end) return cur_node.second + 1;
    
                        if (dict.count(tmp) && !visited.count(tmp)) {
                            q.push(make_pair(tmp, cur_node.second + 1));
                            visited.insert(tmp);
                        }
                    }
                }
            }
            return 0;
        }
    };
  • 相关阅读:
    Java事务
    Mybatis二级缓存问题
    183.面试题 17.14. 最小K个数(快速排序)
    182. 跟着三叶学最短路径问题(存图方式)
    181. 差分数组学习
    AI大视觉(二十) | 小目标检测的tricks汇总
    CentOS7 上安装 mysql-5.7.26
    如何欺骗 Go Mod?
    .netcore docker常用命令-持续补充
    转载:登录后,用户配置被修改的处理方法
  • 原文地址:https://www.cnblogs.com/dongguangqing/p/3727377.html
Copyright © 2011-2022 走看看