994. 腐烂的橘子(Medium)/ 582. 杀死进程(M)/ 二维矩阵DFS、BFS、并查集问题

class Solution:
	# BFS
    def orangesRotting(self, grid: List[List[int]]) -> int:
        row, col, time = len(grid), len(grid[0]), 0
        directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
        queue = []
        # 把腐烂橘子的坐标入队
        for i in range(row):
            for j in range(col):
                if grid[i][j] == 2:
                    queue.append((i, j, time))

        # bfs
        while queue:
            i, j, time = queue.pop(0)
            for di, dj in directions:
                if 0 <= i + di < row and 0 <= j + dj < col and grid[i + di][j + dj] == 1:
                    grid[i + di][j + dj] = 2 # 把腐烂橘子邻近的新鲜橘子变成腐烂橘子
                    queue.append((i + di, j + dj, time + 1))

        # 如果还有新鲜橘子,就返回-1
        for row in grid:
            if 1 in row: return -1

        return time

在这里插入图片描述

582. 杀死进程

在这里插入图片描述

  • 知乎题解
  • 根据题目给出的父子关系建立有向图,然后从kill节点开始向下进行bfs,遍历到的所有进程都是会连带被杀掉的进程,而bfs的队列q就是最终答案
class Solution(object):
    def killProcess(self, pid, ppid, kill):
        """
        :type pid: List[int]
        :type ppid: List[int]
        :type kill: int
        :rtype: List[int]
        """

        childs = {}
        for x, y in zip(pid, ppid):
            if y not in childs:
                childs[y] = []
            childs[y].append(x)

        q = [kill]
        head, tail = 0, 1
        while head < tail:
            now = q[head]
            head += 1
            for next in childs.get(now, []):
                q.append(next)
                tail += 1
        
        return q
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值