leetcode 图相关的题

图相关知识有leetcode207课程表1(有环判断)以及210 课程表2(拓扑排序).

  • 链表遍历
def dfs(n):
	print(n)
	dfs(n)
  • 二叉树遍历
def dfs(n):
	print(n)
	dfs(n.left)
	dfs(n.right)
  • 矩阵的dfs遍历
    联通岛屿等问题
# 1表示陆地,0表示海水,需要求出联通陆地个数(iland_cnt)
mat=[[...]]
VISITED=2 # 直接修改原始矩阵,防止再次访问
LAND = 1
WATER = 0
iland_cnt = 0
for rr in range(mat.shape[0]):
	for cc in range(mat.shape[1]):
		if mat[rr, cc] == LAND: # 陆地才遍历
			iland_cnt += 1
			dfs(mat, rr, cc)

def dfs(mat, rr, cc):
	h, w = mat.shape[0], mat.shape[1]
	if rr >= h or rr <= 0 or cc <= 0 or cc >= w:
		return
	if mat[rr, cc] != LAND:
		return
  mat[rr, cc] = VISITED
	 dfs(mat, rr-1, cc)
	 dfs(mat, rr+1, cc)
	 dfs(mat, rr, cc-1)
	 dfs(mat, rr, cc+1)
  • 多叉树遍历
dfs(root)
def dfs(n):
	for node in n.nodes:
		dfs(node)
  • 图遍历
visited = [False] * n_nodes
g = build_graph() # list[list[]]
for idx in range(node_num):
	dfs(g, idx, visited)

def dfs(g, idx, visited):
	if visited[idx]:
		return
	visited[idx] = True
	for idx in range(g[idx]):
		dfs(g, idx, visited)

遍历链表(只dfs(node))->遍历二叉树(dfs(node.left), dfs(node.right)-> 遍历多叉树 for(n:nodes) dfs(n) ->遍历图:for(n:nodes) visited[n]=True,dfs(n)

  • 图遍历完整示例
def traverse_graph():
    def build_graph(num_nodes, edges):
        g = []
        for _ in range(num_nodes):
            g.append([])
        for e in edges:
            FROM = e[0]
            TO = e[1]
            g[FROM].append(TO)
        return g

    def dfs(g, idx, visited):
        if visited[idx]:
            return
        print(idx)
        visited[idx] = True
        for s in g[idx]:
            dfs(g, s, visited)

    def start_traverse(num_nodes: int, edges: List[List[int]]):
        g = build_graph(num_nodes, edges)
        visited = num_nodes * [False]
        for s in range(num_nodes):
            dfs(g, s, visited)

    """
    0, 1为图的入口,2, 4为出口, 另外有个独立的图 5->6
        0 -> 1 -> 2
        3/^   \>  4
        
        5 -> 6
    """
    edges = [
        [0, 1],
        [1, 2],
        [3, 1],
        [1, 4],
        [5, 6]
    ]
    n_nodes = 7
    start_traverse(n_nodes, edges)

参考:
https://mp.weixin.qq.com/s/7nP92FhCTpTKIAplj_xWpA?forceh5=1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值