2
def containVirus(self, mat: List[List[int]]) -> int:3
m, n = len(mat), len(mat[0])6
i, j, visited, nextInfected7
): # return no. of walls require to quarantined dfs area8
if 0 <= i < m and 0 <= j < n and (i, j) not in visited:9
if mat[i][j] == 2: # Already quarantined cell12
nextInfected.add((i, j)) # add cell which will be infected next day13
return 1 # require one wall to quarantined cell from one side18
dfs(i - 1, j, visited, nextInfected)19
+ dfs(i + 1, j, visited, nextInfected)20
+ dfs(i, j - 1, visited, nextInfected)21
+ dfs(i, j + 1, visited, nextInfected)22
) # traverse all four direction29
): # this loop running "how many days we should installing the walls" times30
# For every day check which area infect more cells31
visited = set() # Using in dfs32
All_nextinfect = set()36
) # here stop store the indices of maximum no. of cells in which we stop spreading of virus this day40
if mat[i][j] == 1 and (i, j) not in visited:42
a = dfs(i, j, visited, nextInfected)44
if len(stop) < len(nextInfected):47
) # leave previous saved area from virus48
stop = nextInfected # pick new area which we want to save49
walls = a # require walls50
p, q = i, j # starting position(indices) of this area52
All_nextinfect = All_nextinfect | nextInfected54
if not stop: # if our job is done i.e. No cell will be infect Later56
ans += walls # add new walls installed this day58
# change each cell value to 2 which will be covered by quarantined area60
if 0 <= p < m and 0 <= q < n and mat[p][q] == 1:67
fun(p, q) # start dfs from start point of quarantined area74
): # set new infected cell value = 1 for iterating next day77
return ans # Final answer