算法与数据结构 / 51

图搜索:BFS、DFS与拓扑顺序

数据结构、边界条件与实现过程。 图搜索:BFS、DFS与拓扑顺序。

阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。

1. Graph Definition

图定义: G=(V,E)G=(V,E)。无向边{a,b}不区分方向;有向边(a,b)与(b,a)是不同的边。邻接关系、权重、自环与重边是否允许,应由题目先声明。

2. Graph Representation

表示方式独立例: 三角图a—b—c—a的邻接表为a:[b,c], b:[a,c], c:[a,b];同一顺序a,b,c的邻接矩阵为[[0,1,1],[1,0,1],[1,1,0]]。网格本身也可视为隐式图,邻居由坐标规则生成。

  • Matrix

  • Adjacency matrix(邻接矩阵)

Adjacency matrix特点:

  1. 需要O(V²)空间;稀疏图通常用邻接表更省空间
  2. Fast query fro edge existence
  3. 添加边通常O(1),新增顶点可能需要扩容矩阵

3. Graph Exploration

通用遍历: 将起点放入工作容器并标记;反复取节点,遍历未标记邻居,标记并加入容器。FIFO容器给BFS,递归/栈给DFS;通常入队时就标记,避免重复扩展。

3.1 BFS(宽度优先)

TC=O(V+E)TC=O(V+E)

BFS层: 起点在距离0;其未访问邻居在距离1;再下一层在距离2。无权图首次发现节点即得到最短边数距离,队列/双列表都可实现层次推进。

3.1.1 Zigzag level oreder traversal of nodes’ values of a binary tree.

Z字形例子: 层序树[3,9,20,null,null,15,7]逐层为[3]、[9,20]、[15,7];交替翻转输出后得到[[3],[20,9],[15,7]],不翻转实际父子关系。

PYTHON · 仅供阅读
class Solution(object):
    def zigzagLevelOrder(self, root):
        if not root:
            return []
        frontier, reverse, ans = [root], False, []
        while frontier:
            next, cur = [], []
            for u in frontier:
                cur.append(u.val)
                if u.left:
                    next.append(u.left)
                if u.right:
                    next.append(u.right)
            ans.append(cur[::-1] if reverse else cur)
            frontier = next
            reverse = not reverse
        return ans

3.1.2 Count the number of islands

Given a 2d grid map of ‘1’s (land) and ‘0’s (water), count the number of islands. And island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are surrounded by water.

岛屿例子: 四行11000/11000/00100/00011按上下左右相连,共3个岛。每遇到未访问陆地,启动一次BFS/DFS并标记整个连通分量。

TC=O(m∗n)TC=O(m*n)

PYTHON · 仅供阅读
def BFS(grid, r, c, marked):
    dr, dc = [-1, 0, 1, 0], [0, 1, 0, -1]  # r=row, c=col
    marked.add((r, c))
    frontier = [(r, c)]
    while frontier:
        next = []
        for r, c in frontier:
            for d in range(4):
                nr, nc = r + dr[d], c + dc[d]
                if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] == '1' \
                        and (nr, nc) not in marked:
                    node = (nr, nc)
                    marked.add(node)
                    next.append(node)
        frontier = next


def numOflands(grid):
    res, marked = 0, set()
    for r in range(len(grid)):
        for c in range(len(grid[0])):
            if grid[r][c] == '1' and (r, c) not in marked:
                res += 1
                BFS(grid, r, c, marked)
    return res

3.1.3 Shortest transformation

Given two words, and a dictionary’s word list, find the length of shortest transformation squence form beginWord to endWord, such that: Only one letter can be changed at time.

单词变换: 用词表hot,dot,dog,lot,log,cog,hit→hot→dot→dog→cog共有5个词;若cog不在允许词表内则无解。每条边只改一个字符,BFS寻找最短序列。

PYTHON · 仅供阅读
import string


def ladderLength(beginWord, endWord, wordList):
    wordList = set(wordList)
    if endWord not in wordList:
        return 0
    ans = 1
    frontier = [beginWord]
    used = set(frontier)
    while frontier:
        next = []
        for word in frontier:
            for p in range(len(word)):
                for c in string.ascii_lowercase:
                    newWord = word[:p] + c + word[p+1:]
                    if newWord == endWord:
                        return ans + 1
                    if newWord in wordList and newWord not in used:
                        used.add(newWord)
                        next.append(newWord)
        frontier = next
        ans += 1
    return 0

3.1.4 Given an undirected graph, return true if and only if it is bipartite.

二分图定义:
二分图又称作二部图,是图论中的一种特殊模型。 设G=(V,E)是一个无向图,如果顶点V可分割为两个互不相交的子集(A,B),并且图中的每条边(i,j)所关联的两个顶点i和j分别属于这两个不同的顶点集(i in A,j in B),则称图G为一个二分图。简而言之,就是顶点集V可分割为两个互不相交的子集,并且图中每条边依附的两个顶点都分属于这两个互不相交的子集,两个子集内的顶点不相邻。

Recall that a graph is bipartite if we can split it’s set of nodes into two independent subsets A and B such that every edge in the graph has one node in A and another node in B.
The graph is given in the following form: graph[i] is a list of indexes j for which the edge between nodes i and j exists. Each node is an integer between 0 and graph.length - 1. There are no self edges or parallel edges: graph[i] does not contain i, and it doesn’t contain any element twice.

二分图: 四环0—1—2—3—0可分为{0,2}与{1,3};三角形无法两色染色。非连通图需从每个尚未访问节点继续检查。

During BFS, the edge that we actually traverse will form a spanning tree. For those edges that we do not traverse, there are two types:

  1. An edge that connects two vertices that are on the same BFS level.
  2. An edge that connects two vertices that are on two consecutive BFS levels.

It is impossible for an edge to connect two vertices on two different BFS levels with the level difference > 1. In such a case, if it is possible, then we could find a path containing less edges between two nodes. this violates the fact that the path between two nodes formed by BFS tree edge is the shortest one.

PYTHON · 仅供阅读
def bfs(graph, visited, u):
    visited[u] = 0
    frontier = [u]
    while frontier:
        next = []
        for u in frontier:
            for v in graph[u]:
                if v not in visited:
                    visited[v] = visited[u] + 1
                    next.append(v)
                elif visited[v] == visited[u]:
                    return False
        frontier = next
    return True


class Solution(object):
    def isBipartite(self, graph):
        visited = {}
        for v in range(len(graph)):
            if v not in visited and not bfs(graph, visited, v):
                return False
        return True

染色法:
对每一个点进行染色操作,只用两种颜色,如果所有的点都染上了色且相邻两个点的颜色不同,如果可以那么这个图就是一个二分图

PYTHON · 仅供阅读
from collections import deque
from typing import List

class Solution:   
    def isBipartite(self, graph: List[List[int]]) -> bool:
        n = len(graph)
        # 0表示还没分组,-1和1表示两种颜色,即两个组
        color = [0 for _ in range(n)]
        for i in range(n):
            # 只考虑没分组的点
            if not color[i]:
                # 分到其中一组,1或-1均可
                queue = deque([i])
                color[i] = 1
                # 开始BFS
                while queue:
                    temp = queue.popleft()
                    col = color[temp]
                    for x in graph[temp]:
                        # 遍历到的已经分过组了,且与i一个组,那么冲突,直接返回False
                        if color[x] == col:
                            return False
                        # 已经分过组,颜色不一致,pass
                        elif color[x] == -col:
                            pass
                        # 没分组的,分到与i相反的组,送入队列
                        else:
                            color[x] = -col
                            queue.append(x)
        #如果遍历完所有的都没有冲突,那么返回True
        return True

3.1.5 Distance to the nearest gate

You are given a m * n 2D grid initialized with these three possible values.

  • -1: A wall
  • 0: Agate
  • INF: Infinity means an empty room

Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.

多源BFS: 把所有门(0)同时放入距离0队列;只扩展可通行的INF空房,墙(−1)不扩展。空房第一次被写入的距离就是离最近门的距离;不可达房间保留INF。

TC=O(M∗N)TC=O(M*N)

PYTHON · 仅供阅读
class Solution(object):
    def wallsAndGates(self, rooms):
        if not rooms:
            return
        dr, dc = [-1, 0, 1, 0], [0, 1, 0, -1]
        N, C = len(rooms), len(rooms[0])
        frontier, INF = [(r, c) for r in range(N) for c in range(C) if rooms[r][c] == 0], \
                        float('inf')
        distance = 0
        while frontier:
            next = []
            for r, c in frontier:
                for d in range(4):
                    nr, nc = r + dr[d], c + dc[d]
                    if 0 <= nr < N and 0 <= nc < C and rooms[nr][nc] == INF:
                        rooms[nr][nc] = distance + 1
                        next.append((nr, nc))
            frontier = next
            distance += 1

整理注: 此实现使用float(‘inf’)作空房哨兵;若题目输入用2147483647,应将INF常量统一为输入约定。

3.2 DFS

TC=O(V+E)TC=O(V+E)

DFS: 进入节点先标记,再对每个未访问邻居递归。完整图遍历还要循环所有顶点以覆盖非连通部分;邻接表时间O(V+E),递归栈最坏O(V)。

3.2.1 Graph Valid Tree

Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), check whether these edges make up a valid tree. (Tree:无环且连通)

树判定例: n=5、边[[0,1],[0,2],[0,3],[1,4]]连通无环;若增加能闭合已有路径的边便有环。无向DFS要忽略来自父节点的回边。

PYTHON · 仅供阅读
from collections import defaultdict
# defaultdict()的作用是在于,当字典里的key不存在但被查找时,返回不是keyError而是默认值
# 默认值:list对应[ ],str对应的是空字符串,set对应set( ),int对应0

def has_cycle(graph, visited, parent, u):
    visited.add(u)
    for v in graph[u]:
        if v != parent:
            if v in visited or has_cycle(graph, visited, u, v):
                return True
    return False


class Solution(object):
    def validTree(self, n, edges):
        visited = set()
        graph = defaultdict(list)
        for edge in edges:
            graph[edge[0]].append(edge[1])
            graph[edge[1]].append(edge[0])
        return not has_cycle(graph, visited, -1, 0) and len(visited) == n

3.2.2 How to determine whether the given directed graph has a cycle or not.

有向环: DFS使用未访问、正在访问、已完成三态。边指向正在访问节点表示当前递归链形成环;指向已完成节点不一定是环。仅靠一个visited集合无法区分。

PYTHON · 仅供阅读
def dfs(directed_graph, visit_status, u):
    # 0 means we are currently still visiting a node
    # 1 means we are done with a node
    visit_status[u] = 0
    for v in directed_graph[u]:
        if v not in visit_status:
            if dfs(directed_graph, visit_status, v):
                return True
        elif visit_status[v] == 0:
            return True
    visit_status[u] = 1
    return False


def has_cycle(directed_graph):
    visit_status = {}
    for v in directed_graph:
        if v not in visit_status and dfs(directed_graph, visit_status, v):
            return True
    return False

3.2.3 Course Schedule

There are a total of n courses you have to take, labeled from 0 to n-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 alist of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

课程顺序: 先修关系[1,0],[2,0],[3,1],[3,2]对应0→1、0→2、1→3、2→3;合法顺序有0,1,2,3或0,2,1,3。发现有向环则无法完成全部课程。

Note:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices.
  2. You may assume that there are no duplicate edges in the input prerequisites.
PYTHON · 仅供阅读
from collections import defaultdict


class Solution(object):
    def findOrder(self, numCourses, prerequisites):
        graph = defaultdict(list)
        for p in prerequisites:
            graph[p[1]].append(p[0])
        courses = []
        visited = [-1] * numCourses

        def dfs(u):
            visited[u] = 0
            for v in graph[u]:
                if visited[v] == 0 or (visited[v] == -1 and not dfs(v)):
                    return False
            visited[u] = 1
            courses.append(u)
            return True

        for u in range(numCourses):
            if visited[u] == -1 and not dfs(u):
                return []
        courses.reverse()
        return courses

整理参考资料