Approach
Depth-first search
For Contain Virus, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 59 lines of Python from the credited upstream file contain-virus.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class Solution(object):5 def containVirus(self, grid):6 """7 :type grid: List[List[int]]8 :rtype: int9 """10 directions = [(0, 1), (0, -1), (-1, 0), (1, 0)]11 12 def dfs(grid, r, c, lookup, regions, frontiers, perimeters):13 if (r, c) in lookup:14 return15 lookup.add((r, c))16 regions[-1].add((r, c))17 for d in directions:18 nr, nc = r+d[0], c+d[1]19 if not (0 <= nr < len(grid) and \20 0 <= nc < len(grid[r])):21 continue22 if grid[nr][nc] == 1:23 dfs(grid, nr, nc, lookup, regions, frontiers, perimeters)24 elif grid[nr][nc] == 0:25 frontiers[-1].add((nr, nc))26 perimeters[-1] += 127 28 result = 029 while True:30 lookup, regions, frontiers, perimeters = set(), [], [], []31 for r, row in enumerate(grid):32 for c, val in enumerate(row):33 if val == 1 and (r, c) not in lookup:34 regions.append(set())35 frontiers.append(set())36 perimeters.append(0)37 dfs(grid, r, c, lookup, regions, frontiers, perimeters)38 39 if not regions: break40 41 triage_idx = frontiers.index(max(frontiers, key = len))42 for i, region in enumerate(regions):43 if i == triage_idx:44 result += perimeters[i]45 for r, c in region:46 grid[r][c] = -147 continue48 for r, c in region:49 for d in directions:50 nr, nc = r+d[0], c+d[1]51 if not (0 <= nr < len(grid) and \52 0 <= nc < len(grid[r])):53 continue54 if grid[nr][nc] == 0:55 grid[nr][nc] = 156 57 return result58 59