← 返回 openai 的题目列表Infectious Disease Spread (Infection Propagation)
类型:online_judge
Infectious Disease (Infection Propagation)
You are given a data structure describing how infection can spread in a population (e.g., a contact graph, contact logs, or a 2D grid). Some individuals are infected at time 0. Infection spreads in discrete steps: at each step, every infected individual causes all directly connected (in-contact) uninfected individuals to become infected in the next step.
Implement a function that returns:
the minimum number of time steps needed to infect all reachable individuals;
if there exists any individual that can never be infected (disconnected from all sources), return a sentinel value such as -1.
Notes
Clearly define the input representation:
Graph: n nodes, edge list edges, initial infected set sources.
Grid: m x n grid with encodings for infected/uninfected/blocked.
Output is a single integer (steps or -1).
Constraints
The input can be large; aim for linear or near-linear time.
Sample tests
Input: graph n=4, edges=[[0,1],[1,2],[2,3]], sources=[0] => Output: 3
Input: graph n=4, edges=[[0,1],[2,3]], sources=[0] => Output: -1
Input: grid [[2,1,1],[1,1,0],[0,1,1]] (2=infected, 1=susceptible, 0=blocked) => Output: 4
Input: grid [[2,1,1],[0,1,1],[1,0,1]] => Output: -1
Input: grid [[0,2]] => Output: 0
Example
Input
4
3
0 1
1 2
2 3
1
0
Output
3