Chapter 4: Trees and Graph

Tree 和 Graph 本质上是刻画事物之间的关系的data structure,根据关系的特性决定使用Tree还是Graph。无论输入给定了什么数据结构,只要路径空间是二维的,我们就应该使用这两种数据结构

知识解析

4.4 Graph的表述

类似于Tree,Graph主要用于描述事物之间的关系,只要每个节点的parent可能有多个(常见),或者有可能存在cycle,就必须用graph而不是tree来解决。Graph由Vertices (点)和 Edges (边) 组成

Graph有4种表述方式 (representation) . 这4种表述方式都是完备的,也就是说给出其中任何一个表述方式,我都可以画出这个图而不会有任何歧义。

4.4.1 用 object GraphNode代表vertex,用 array of GraphNode代表从vertex出发的edges指向的children node, 即

class GraphNode:
  def __init__(val):
    self.val = val
    self.children: List[GraphNode] = [] # array of GraphNode

4.4.2 【基准表述】用 2d array 的index (或者hash的key)代表vertex的id,用subarray代表edges指向的children ids, 即

edge_matrix = [
  [ 1, 2 ], # children ids for node 0
  [ 2 ],    # children ids for node 1
  [ ],      # children ids for node 2
]

# or use a hash
vertice_children_map = {
  0: [1,2],
  1: [2]
}

4.4.3 用 2d array 的index 代表vertex的id,用subarray中value为1的index来代表children id,即

4.4.4 用 0 ~ n 的整数代表vertex的id, 用array of pairs代表所有的edges, 每个pair代表指出和指入的vertex id,一般先转换成 4.4.2 基准表述再进行处理。即

模式识别

4.5 BFS 和 DFS

4.8 Graph Traversal

e.g.1 There are N rooms and you start in room 0. Each room may have some keys to access the next room. Return true if and only if you can enter every room. (LeetCode: Keys and Rooms)

e.g.2 There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]. Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? ( LeetCode: Course Schedule )

4.9 Topological Sort

Topological Sort是指对于一个Graph,找到一个sequence使得任何一条edge的parent,都出现在这条edge的child之前。 一种方法是最后把 visited 反向,最后 visited 就是一条满足条件的sequence;* 第二种方法是用 Kahn's Algorithm for Topological Sorting (仅供参考)

e.g.1 There are a total of n courses you have to take labelled from 0 to n - 1. Some courses may have prerequisites, for example, if prerequisites[i] = [ai, bi] this means you must take the course bi before the course ai. Given the total number of courses numCourses and a list of the prerequisite pairs, return the ordering of courses you should take to finish all courses. ( LeetCode: Course Schedule II )

e.g.2 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. (LeetCode: Alien Dictionary)

Last updated

Was this helpful?