[Leetcode] 269. Alien Dictionary 解题报告

本文介绍了一种基于拓扑排序的算法,用于确定一种未知外星语言中字母的正确顺序。通过分析字典中按该语言规则排序的单词列表,可以推导出字母间的先后关系。

题目

There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.

Example 1:
Given the following words in dictionary,

[
  "wrt",
  "wrf",
  "er",
  "ett",
  "rftt"
]

The correct order is: "wertf".

Example 2:
Given the following words in dictionary,

[
  "z",
  "x"
]

The correct order is: "zx".

Example 3:
Given the following words in dictionary,

[
  "z",
  "x",
  "z"
]

The order is invalid, so return "".

Note:

  1. You may assume all letters are in lowercase.
  2. You may assume that if a is a prefix of b, then a must appear before b in the given dictionary.
  3. If the order is invalid, return an empty string.
  4. There may be multiple valid order of letters, return any one of them is fine.

思路

使用拓扑排序是这一道题目的正解。我们可以利用这道题目总结一下拓扑排序的实现框架:

1)定义两个哈希表,一个用来表示每次出现过的字符的入度,另一个来存一个字符指向的字符集合。

2)每次找出一个入度为0的字符,并且更新这个字符指向的字符集入度减1。如果在没有遍历完所有字符的情况下找不到入度为0的字符,那么说明没有合法的拓扑排序,返回“”。如果在一次遍历过程中出现了多个入度为0的字符,说明拓扑排序的解不唯一,任意选择其中一个就可以了。

代码

class Solution {
public:
    string alienOrder(vector<string>& words) {
        if(words.size() == 0) {
            return "";  
        }
        unordered_map<char, int> indegree;  
        unordered_map<char, multiset<char>> hash;  
        for(auto word: words) {  
            for(auto ch: word) {
                indegree[ch] = 0; 
            }
        }
        for(int i = 1; i < words.size(); i++) {  
            int k = 0, len1 = words[i-1].size(), len2 = words[i].size();  
            while(words[i-1][k] == words[i][k]) {
                ++k;
            }  
            if(k >= min(len1, len2)) {
                continue;
            }
            ++indegree[words[i][k]];
            hash[words[i - 1][k]].insert(words[i][k]);  
        }  
        string ret;  
        for(int i = 0; i < indegree.size(); i++) {  
            char ch = ' ';  
            for(auto val: indegree) {
                if(!val.second) { 
                    ch = val.first; 
                    break; 
                } 
            }
            if(ch == ' ') {
                return ""; 
            }
            ret += ch;
            --indegree[ch];  
            for(auto val: hash[ch]) {
                --indegree[val];
            }
        }  
        return ret;  
    }
};
<think>我们被要求使用中文回答,并且需要遵循严格的格式要求。 用户的问题是关于networkx库中`nx.topological_sort()`函数的使用和示例。 根据引用,我们知道NetworkX是一个用于复杂网络的Python库,而拓扑排序是有向无环图(DAG)中节点的一种线性排序,使得对于每一条有向边(u, v),节点u都出现在节点v之前。 我们将按照以下步骤回答: 1. 解释拓扑排序的概念。 2. 介绍`nx.topological_sort()`函数的基本用法。 3. 提供一个完整的示例代码,包括创建有向图、进行拓扑排序以及输出结果。 4. 注意:在示例代码中,我们将使用NetworkX创建一个小型的有向无环图。 同时,根据系统指令,我们需要生成相关问题。 注意:在回答中,我们引用了NetworkX官方文档(引用[1]和引用[3]),因此会在适当的地方添加引用标识。 开始回答:</think>### NetworkX 中 `nx.topological_sort()` 函数的使用与示例 拓扑排序是针对**有向无环图(DAG)** 的节点线性排序算法,使得对于任意有向边 \((u \to v)\),节点 \(u\) 总出现在节点 \(v\) 之前。`nx.topological_sort()` 是 NetworkX 库中实现该算法的核心函数[^1]。 --- #### **基本用法** ```python import networkx as nx # 创建有向图 G = nx.DiGraph() edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D")] G.add_edges_from(edges) # 拓扑排序 sorted_nodes = list(nx.topological_sort(G)) print(sorted_nodes) # 输出:['A', 'C', 'B', 'D'] 或 ['A', 'B', 'C', 'D'](合法排序不唯一) ``` - **输入要求**:图必须为有向无环图(DAG),若图含环会抛出 `NetworkXUnfeasible` 异常。 - **返回值**:节点的拓扑排序列表(可能有多个合法结果,函数返回其中一种)。 --- #### **完整示例:课程依赖关系排序** 假设课程依赖关系如下: - 数据结构依赖编程基础 - 算法依赖数据结构 - 机器学习依赖算法和数学 ```python import networkx as nx # 定义课程依赖图 G = nx.DiGraph() G.add_edges_from([ ("编程基础", "数据结构"), ("数据结构", "算法"), ("算法", "机器学习"), ("数学", "机器学习") ]) # 拓扑排序(确保无循环依赖) try: course_order = list(nx.topological_sort(G)) print("课程学习顺序:", course_order) except nx.NetworkXUnfeasible: print("图中存在循环依赖,无法排序!") # 输出示例:['数学', '编程基础', '数据结构', '算法', '机器学习'] ``` --- #### **关键注意事项** 1. **检测环**:排序前可用 `nx.is_directed_acyclic_graph(G)` 验证是否为 DAG。 2. **多结果处理**:若需所有可能排序,使用 `list(nx.all_topological_sorts(G))`。 3. **性能**:时间复杂度 \(O(V+E)\)(\(V\) 为节点数,\(E\) 为边数),适合大型图处理[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值