[A scenario to code] How long will it take for all of us to get covid19?
\[A scenario to code\] How long will it take for all of us to get covid19?
PS: Don’t scroll, if you’re looking for anything related to covid19 news, this post is not contributing to any data points or news related… -
\[A scenario to code\] How long will it take for all of us to get covid19?
PS: Don’t scroll, if you’re looking for anything related to covid19 news, this post is not contributing to any data points or news related to outbreak!
It’s me, normalizing a coding a problem to derive how important social distancing is, and even if the spread is just four-way.
Here is a problem —
> In a hypothetical world, where all the humans can stand in an m\*n grid and at any given day, the human grid can have the following values in the cell:
> Value 0 : The cell is empty
> Value 1 : The human is not infected
> Value -1 : The human is infected
> Every day, a non-infected human can infect its neighboring human in the four directions (up/down/left/right).
> We need to find the number of days, that will go by so that all the humans in the human grid are infected. If that is impossible, we should return -1.
For e.g. a following human grid —

10 \* 10 grid with 100 humans, 1 infected
It will take 18 days to get everyone affected!

10 \* 10 grid with 100 humans, all infected
Here is a solution, that takes the human grid as input and return the number of days—
`
/\\\\*
\* Assuming the humans can stand in a grid of some mXn
\ @param* humans
\ @return* \*/
*public int infectedHumans(int\[\]\[\] humans) {
if(null == humans || humans.length == 0){
return 0;
}
int rows = humans.length; int cols = humans\[0\].length;
/\\\
\* We will use infectedHumans queue to do the BFS
\/ Queue
int days = 0;
/\\\ \* If every one is infected, then we can return 0 the current moment \/ if(nonInfectedHumans == 0) return days;
/\\* \* Assuming virus can be passed in 4 directions in the cells up/down/lef/right \/ int\[\]\[\] directions = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; /\\* \* Let's traverse in the four directions \/ while(!infectedHumans.isEmpty()){ ++days; int size = infectedHumans.size(); for(int i = 0 ; i < size ; i ++){ int \[\] currentPos = infectedHumans.poll(); for (int \[\] move : directions){ int nextMoveX = currentPos\[0\] + move\[0\]; int nextMoveY = currentPos\[1\] + move\[1\];
// if it's a valid move, not a infected human move || not an empty move
if(nextMoveX < 0 || nextMoveY < 0 || nextMoveX >= rows || nextMoveY >= cols || humans\[nextMoveX\]\[nextMoveY\] == 0 || humans\[nextMoveX\]\[nextMoveY\] == -1) continue;
humans\[nextMoveX\]\[nextMoveY\] = -1;
infectedHumans.offer(new int\[\] {nextMoveX, nextMoveY});
nonInfectedHumans--;
}
}
}
return nonInfectedHumans == 0 ? (days - 1) : -1;
}
`
That’s it!
Stay safe, stay connected, maintain social distancing, we are all in this together! let’s be stronger than ever, help community and we can succeed together!
— Gaurav
Responses