这是一道 Google Coding 面试真题,题目分为三个部分,逐步增加传播和恢复规则,主要考察二维网格模拟与状态更新。
Original Interview Question
Plant Epidemic Simulation
Given an M×N grid of plants, implement epidemic_duration() to calculate how long an epidemic lasts.
Part 1: Each cell is . (uninfected) or X (infected). Every day, an uninfected plant becomes infected if at least T of its 8 neighbors are infected. All changes happen simultaneously. Return the number of days with new infections.
Part 2: Adds I, an immune plant that can never be infected. Other rules remain unchanged.
Part 3: Adds parameter D. An infected plant heals after D days and becomes immune (I). Return the number of days until no infected plants remain. If there are no initial infections, return 0.
给定一个 M×N 的植物网格,实现函数 epidemic_duration(),计算疫情持续的天数。
第一部分: 每个格子为未感染 . 或已感染 X。每天,如果未感染植物周围 8 个方向至少有 T 株感染植物,它就会被感染。当天所有变化同时发生。返回发生新感染的天数。
第二部分: 新增免疫植物 I,永远不会被感染,其他规则不变。
第三部分: 新增参数 D,感染植物经过 D 天后恢复并变成 I。此时返回所有感染植物消失所需的天数。如果初始没有感染植物,返回 0。
Example
Input:
Grid = [X, ., .]
T = 1
Day 1: [X, X, .]
Day 2: [X, X, X]
Output: 2Solution Approach
这道题可以通过逐天模拟解决。每一天遍历网格,统计周围感染植物的数量,再统一更新状态,避免当天新增的感染影响其他格子的判断。
第二部分只需要跳过免疫植物。第三部分需要额外记录感染天数,并在 D 天后将植物转为免疫状态。
关键在于正确处理每天的同步更新,以及第三部分感染和恢复状态的变化。
CSOAHELP 持续整理真实科技公司面试题,也设计贴近业务场景的练习题,提供 Mock Interview、系统设计辅导和实时面试思路支持。
我们也有代面试,面试辅助,OA代写等服务助您早日上岸~

