question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
maximum-product-of-three-numbers | Python beats 100% & 100% in two ways easy understand nO(logn) & O(n) | python-beats-100-100-in-two-ways-easy-un-mip6 | python\n def maximumProduct(self, nums: List[int]) -> int:\n nums.sort()\n return max(nums[0]*nums[1]*nums[-1] , nums[-1]*nums[-2]*nums[-3])\n\ | macqueen | NORMAL | 2019-11-13T10:15:36.031528+00:00 | 2019-11-13T10:15:36.031567+00:00 | 316 | false | ```python\n def maximumProduct(self, nums: List[int]) -> int:\n nums.sort()\n return max(nums[0]*nums[1]*nums[-1] , nums[-1]*nums[-2]*nums[-3])\n```\nsort make a n*log(n) time and it beats 100% and 100%\nthis way can only solve in three numbers\nsecond way is a normal idea solve a normal problom:\n\n```python\nclass Solution:\n def maximumProduct(self, nums: List[int]) -> int:\n minOne = sys.maxsize # most small\n minTwo = sys.maxsize # second small\n maxOne = - sys.maxsize # most big\n maxTwo = - sys.maxsize # second big\n maxThree = - sys.maxsize\n\n for i in range(len(nums)):\n if nums[i] <= minOne:\n minTwo = minOne\n minOne = nums[i]\n elif nums[i] <= minTwo: # <\n minTwo = nums[i]\n \n if nums[i] >= maxOne:\n maxThree = maxTwo\n maxTwo = maxOne\n maxOne = nums[i]\n elif nums[i] >= maxTwo:\n maxThree = maxTwo\n maxTwo = nums[i]\n elif nums[i] >= maxThree:\n maxThree = nums[i]\n return max(maxOne*maxTwo*maxThree , maxOne*minOne*minTwo)\n```\nBecause there are positive and negative number\nwhen only positive in last result , we return \n```\nmaxOne*maxTwo*maxThree\n```\nwhen there has 2 negative number in our result, it return :\n```\nmaxOne*minOne*minTwo\n```\n\n**If it helps you , Please give me a vote star\nThanks** | 3 | 1 | [] | 0 |
maximum-product-of-three-numbers | Easy solution - without sorting | easy-solution-without-sorting-by-pooja04-t5o3 | Runtime: 44 ms, faster than 92.47% of C++ online submissions for Maximum Product of Three Numbers.\nMemory Usage: 10.9 MB, less than 100.00% of C++ online submi | pooja0406 | NORMAL | 2019-08-23T07:08:17.619807+00:00 | 2019-08-23T07:08:17.619843+00:00 | 492 | false | Runtime: 44 ms, faster than 92.47% of C++ online submissions for Maximum Product of Three Numbers.\nMemory Usage: 10.9 MB, less than 100.00% of C++ online submissions for Maximum Product of Three Numbers.\n\n```\nint maximumProduct(vector<int>& nums) {\n \n int n = nums.size();\n int minOne = INT_MAX;\n int minTwo = INT_MAX;\n int maxOne = INT_MIN;\n int maxTwo = INT_MIN;\n int maxThree = INT_MIN;\n \n for(int i=0; i<n; i++)\n {\n if(nums[i] <= minOne)\n {\n minTwo = minOne;\n minOne = nums[i];\n } else if(nums[i] < minTwo)\n {\n minTwo = nums[i];\n }\n \n if(nums[i] >= maxOne)\n {\n maxThree = maxTwo;\n maxTwo = maxOne;\n maxOne = nums[i];\n } else if(nums[i] >= maxTwo)\n {\n maxThree = maxTwo;\n maxTwo = nums[i];\n }\n else if(nums[i] > maxThree)\n {\n maxThree = nums[i];\n }\n }\n \n return max(maxOne*maxTwo*maxThree, maxOne*minOne*minTwo);\n } | 3 | 0 | ['C++'] | 1 |
maximum-product-of-three-numbers | Python solution | python-solution-by-zitaowang-393d | O(n log n) time O(n) space:\n\nclass Solution(object):\n def maximumProduct(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n | zitaowang | NORMAL | 2018-10-12T16:06:07.260184+00:00 | 2018-10-23T15:45:20.965435+00:00 | 539 | false | O(n log n) time O(n) space:\n```\nclass Solution(object):\n def maximumProduct(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n nums = sorted(nums)\n if nums[0] >= 0:\n return nums[-3]*nums[-2]*nums[-1]\n elif nums[1] < 0:\n return max(nums[-3]*nums[-2]*nums[-1], nums[0]*nums[1]*nums[-1])\n else:\n return nums[-3]*nums[-2]*nums[-1]\n```\nO(n) time O(1) space:\n```\nclass Solution(object):\n def maximumProduct(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n min1, min2 = float(\'inf\'), float(\'inf\')\n max1, max2, max3 = -float(\'inf\'), -float(\'inf\'), -float(\'inf\')\n \n for n in nums:\n if n < min1:\n min1, min2 = n, min1\n elif n < min2:\n min2 = n\n if n > max3:\n max1, max2, max3 = max2, max3, n\n elif n > max2:\n max1, max2 = max2, n\n elif n > max1:\n max1 = n\n if min1 >= 0:\n return max3*max2*max1\n elif min2 < 0:\n return max(max3*max2*max1, min1*min2*max3)\n else:\n return max3*max2*max1\n``` | 3 | 0 | [] | 0 |
maximum-product-of-three-numbers | Python Easy with Explaination | python-easy-with-explaination-by-reknix-shmv | \ndef maximumProduct(self, nums):\n nums.sort()\n max_num = 0\n # if all negative, or all positive, or only one negative number. In this case, take 3 r | reknix | NORMAL | 2017-06-25T03:11:34.771000+00:00 | 2017-06-25T03:11:34.771000+00:00 | 621 | false | ```\ndef maximumProduct(self, nums):\n nums.sort()\n max_num = 0\n # if all negative, or all positive, or only one negative number. In this case, take 3 rightmost number \n if nums[-1] < 0 or nums[0] >= 0 or (nums[0] < 0 and nums[1] > 0):\n max_num = nums[-1] * nums[-2] * nums[-3]\n # if two or more negative numbers, compare rightmost 3 nums or 2 left most * 1 rightmost\n else:\n max_num = max(nums[-3] * nums[-2] * nums[-1], nums[0] * nums[1] * nums[-1])\n return max_num\n``` | 3 | 0 | [] | 0 |
maximum-product-of-three-numbers | BEST C++ SOLUTION || BEATS 100% || EASY EXPLANATION || | best-c-solution-beats-100-easy-explanati-omht | IntuitionFind the three largest numbers.Find the two smallest numbers (to handle cases with negative numbers).Compute both possible products:largest1 * largest2 | rameeta | NORMAL | 2025-02-18T18:47:02.925397+00:00 | 2025-02-18T18:56:31.288184+00:00 | 445 | false | # Intuition
Find the three largest numbers.
Find the two smallest numbers (to handle cases with negative numbers).
Compute both possible products:
largest1 * largest2 * largest3
smallest1 * smallest2 * largest1
Return the maximum of the two.
# Approach
Instead of sorting (which is O(N log N)), we can find the top three maximum numbers in a single pass (O(N)) using three variables:
Step 1: Maintain Three Variables
max1 → Largest number
max2 → Second largest
max3 → Third largest
Every time you iterate through nums, update them accordingly.
Step 2: Also Track Two Smallest Numbers
Since two negative numbers can give a large positive product, we also need:
min1 → Smallest number
min2 → Second smallest
Approach: Updating Values on the Go
For each num in nums:
>If num is greater than max1, shift all down (max3 = max2, max2 = max1, max1 = num).
>Else if num is greater than max2, shift down (max3 = max2, max2 = num).
>Else if num is greater than max3, update max3 = num.
>If num is smaller than min1, shift (min2 = min1, min1 = num).
>Else if num is smaller than min2, update min2 = num.
Once you get max1, max2, max3, min1, min2, the maximum product is:
max(max1 * max2 * max3, min1 * min2 * max1)
# Complexity
- Time complexity:
O(N)
- Space complexity:
O(1)
DO UPVOTE !!!!!!
# Code
```cpp []
class Solution {
public:
int maximumProduct(vector<int>& nums) {
int max1 = INT_MIN, max2 = INT_MIN , max3 =INT_MIN;
int min1 = INT_MAX , min2 = INT_MAX;
for( int num : nums){
if(num > max1){
max3= max2;
max2 = max1;
max1 = num;
}
else if(num > max2){
max3 = max2;
max2 = num ;
}
else if(num > max3){
max3 = num;
}
if(num < min1){
min2 = min1;
min1 = num;
}
else if(num < min2){
min2 = num;
}
}
long long option1 = (long long)max1 * max2 * max3;
long long option2 = (long long)min1 * min2 * max1;
return max(option1, option2);
}
};
/*sort(nums. begin(), nums.end());
int n = nums.size();
int ch1= (nums[n-1] * nums[n-2] * nums[n-3]);
int ch2 = (nums[0] * nums[1] * nums[n-1]);
return max(ch1 , ch2);*/
``` | 2 | 0 | ['C++'] | 0 |
maximum-product-of-three-numbers | Java || Single-Pass Linear Scan || time complexity : O(n) | java-single-pass-linear-scan-time-comple-lqy7 | Complexity
Time complexity: O(n)
Space complexity: O(1)
Code | shikhargupta0645 | NORMAL | 2025-02-02T02:34:01.405800+00:00 | 2025-02-02T02:34:01.405800+00:00 | 574 | false |
# Complexity
- Time complexity: O(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int maximumProduct(int[] nums) {
int max1 = Integer.MIN_VALUE;
int max2 = Integer.MIN_VALUE;
int max3 = Integer.MIN_VALUE;
int min1 = Integer.MAX_VALUE;
int min2 = Integer.MAX_VALUE;
for(int i=0; i<nums.length; i++){
if(nums[i] > max1){
max3 = max2;
max2 = max1;
max1 = nums[i];
}
else if(nums[i] > max2){
max3 = max2;
max2 = nums[i];
}
else if(nums[i] > max3){
max3 = nums[i];
}
if(nums[i] < min1){
min2 = min1;
min1 = nums[i];
}
else if(nums[i] < min2){
min2 = nums[i];
}
}
return Math.max(max1 * min1 * min2, max1 * max2 * max3);
}
}
``` | 2 | 0 | ['Java'] | 0 |
maximum-product-of-three-numbers | BEATS 100%, O(N), SOLUTION | beats-100-on-solution-by-sahil_sr7-khnu | Intuition 🤔To find the maximum product of three numbers in an array, we need to consider both the largest three numbers (positive or negative) and the smallest | sahilrashid10 | NORMAL | 2025-01-28T09:48:12.792756+00:00 | 2025-01-28T09:48:12.792756+00:00 | 509 | false | # Intuition 🤔
To find the maximum product of three numbers in an array, we need to consider both the largest three numbers (positive or negative) and the smallest two numbers (in case they are negative) combined with the largest number. This ensures that we capture both possible scenarios for the highest product.
# Approach 🚀
1. **Tracking Maximums and Minimums**:
- Use three variables (`m1`, `m2`, `m3`) to keep track of the **three largest numbers** in the array.
- Use two variables (`n1`, `n2`) to keep track of the **two smallest numbers** in the array.
2. **Single Pass**:
- Iterate through the array once.
- For each number, update the three largest numbers (`m1`, `m2`, `m3`) and two smallest numbers (`n1`, `n2`) efficiently.
3. **Calculate Maximum Product**:
- Compute two potential products:
- Product of the top three largest numbers: `m1 * m2 * m3`.
- Product of the two smallest numbers (which could be negative) and the largest number: `n1 * n2 * m1`.
4. **Return the Maximum**:
- Compare the two products and return the larger one.
# Complexity 📊
- **Time Complexity**:
$$O(n)$$ - We iterate through the array once to find the largest and smallest numbers.
- **Space Complexity**:
$$O(1)$$ - Only a constant amount of extra space is used for variables.
# Code
```cpp []
//OPTIMAL T=O(n) S=O(1)
class Solution {
public:
int maximumProduct(vector<int>& nums) {
// Initialize the largest and smallest values
int m1 = INT_MIN, m2 = INT_MIN, m3 = INT_MIN;
int n1 = INT_MAX, n2 = INT_MAX;
for (int x : nums) {
// Update largest three numbers
if (x > m1) {
m3 = m2;
m2 = m1;
m1 = x;
} else if (x > m2) {
m3 = m2;
m2 = x;
} else if (x > m3) {
m3 = x;
}
// Update smallest two numbers
if (x < n1) {
n2 = n1;
n1 = x;
} else if (x < n2) {
n2 = x;
}
}
// Calculate both potential maximum products
int product1 = m1 * m2 * m3;
int product2 = m1 * n1 * n2;
return max(product1, product2);
}
};
//BRUTE FORCE T=O(n*logn) S=O(1)
// class Solution {
// public:
// int maximumProduct(vector<int>& nums) {
// sort(nums.begin(), nums.end());
// int n = nums.size();
// int p1=nums[n-1], p2=1, j=n-1, i=0;
// while(i<3){
// p2 *= nums[j];
// if(i<2)
// p1 *= nums[i];
// j--;
// i++;
// }
// return max(p1, p2);
// }
// };
``` | 2 | 0 | ['C++'] | 0 |
maximum-product-of-three-numbers | Finding the GOLDEN Trio ✨ | 2 Methods 🔥 | Simple Explanation + Illustration ⭐ | JAVA 🚀 | finding-the-golden-trio-2-methods-simple-402q | IntuitionTo find the maximum product of any three numbers in an array, we must consider two scenarios:The three largest numbers in the array.
The two smallest n | supreme_undy014 | NORMAL | 2025-01-26T14:35:54.607272+00:00 | 2025-01-26T14:39:41.141289+00:00 | 259 | false | # Intuition
To find the maximum product of any three numbers in an array, we must consider two scenarios:
The three largest numbers in the array.
The two smallest numbers (most negative) multiplied by the largest number. This is because two negative numbers produce a positive product, which might be larger than the product of the three largest numbers.
# Approach
Track Extremes:
Use variables to keep track of the three largest numbers (max1, max2, max3) and the two smallest numbers (min1, min2).
Single Pass:
Traverse the array once:
Update max1, max2, max3 whenever a larger number is found.
Update min1, min2 whenever a smaller number is found.
Compute the Maximum Product:
The result is the maximum of:
The product of the three largest numbers: max1 * max2 * max3.
The product of the two smallest numbers and the largest number: min1 * min2 * max1.
Return the Result:
Use Math.max to determine the larger of the two products.
# Illustration:
Consider the array: [-10, -10, 5, 2].
Initialize:
max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE
min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE
Traverse the array:
-10: Update min1 = -10, min2 = Integer.MAX_VALUE
-10: Update min2 = -10, min1 = -10
5: Update max1 = 5, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE
2: Update max2 = 2, max3 = Integer.MIN_VALUE
Compute products:
max1 * max2 * max3 = 5 * 2 * -10 = -100
max1 * min1 * min2 = 5 * -10 * -10 = 500
Result:
Maximum product = 500.
# Complexity
- Time complexity:
O(n)
- Space complexity:
<O(1)
# Code
# METHOD 1 (Single pass through array)
```java []
class Solution {
public int maximumProduct(int[] nums) {
int max1 = Integer.MIN_VALUE;
int max2 = Integer.MIN_VALUE;
int max3 = Integer.MIN_VALUE;
int min1 = Integer.MAX_VALUE;
int min2 = Integer.MAX_VALUE;
for(int i=0; i<nums.length; i++)
{
if(nums[i] >= max1){
max3 = max2;
max2 = max1;
max1 = nums[i];
}
else if(nums[i] >= max2){
max3 = max2;
max2 = nums[i];
}
else if(nums[i] > max3) max3 = nums[i];
if(nums[i] <= min1){
min2 = min1;
min1 = nums[i];
}
else if(nums[i] < min2) min2 = nums[i];
}
return Math.max(max1 * max2 * max3,max1 * min1 * min2);
}
}
```
# METHOD 2 (Basic SORTING)
This is basically just sorting and checking if the product of the top 3 numbers are more or the product of the first number and the last two numbers are maximum, **However this takes more time.**
**Time complexity -> O(nlogn)**
**Space complexity -> O(1)**
```java []
import java.util.Arrays;
class Solution {
public int maximumProduct(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
return Math.max(nums[n - 1] * nums[n - 2] * nums[n - 3], nums[0] * nums[1] * nums[n - 1]);
}
}
```
Hope this solution clears everything up! If you found it helpful, give it a thumbs up and don’t hesitate to reach out if you have any more questions or need further guidance. Keep pushing forward—your progress is just beginning! 🚀

| 2 | 0 | ['Array', 'Math', 'Java'] | 0 |
maximum-product-of-three-numbers | Easy one liner solution | easy-one-liner-solution-by-karan-s1ngh-xyuc | Approachnum.sort() sorts the list in ascending ordernums[-1]*nums[-2]*nums[-3] gives the product of 3 maximum number (positive)nums[0]*nums[1]*nums[-1] gives th | Karan-S1ngh | NORMAL | 2024-12-28T17:32:06.278641+00:00 | 2024-12-30T19:57:32.780408+00:00 | 492 | false | # Approach
num.sort() sorts the list in ascending order
nums[-1]*nums[-2]*nums[-3] gives the product of 3 maximum number (positive)
nums[0]*nums[1]*nums[-1] gives the product of 2 biggest negative number not considering the negative sign and the biggest positive number.
This is done as product of 2 negative number is always a positive number since we take 2 largest negative number without sign
so eg, [-100,-98,-6,0,1,2]
here the product of -100,-98,-6 will be a negative number
so we take -100,-98 and 2 to get the max product.
max of these will give the largest product possible
# Code
```python3 []
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
nums.sort()
return max(nums[-1]*nums[-2]*nums[-3],nums[0]*nums[1]*nums[-1])
``` | 2 | 0 | ['Python3'] | 0 |
maximum-product-of-three-numbers | Easy Solution in Java | easy-solution-in-java-by-tamilarasanmuru-z6ul | Intuition\nTo find the maximum product of three numbers from the array, there are two possible candidates:\n\n1.The product of the largest three numbers in the | TamilarasanMurugan | NORMAL | 2024-09-25T10:05:31.187498+00:00 | 2024-09-25T10:05:31.187535+00:00 | 40 | false | # Intuition\nTo find the maximum product of three numbers from the array, there are two possible candidates:\n\n1.The product of the largest three numbers in the array.\n2.The product of the two smallest numbers (possibly negative) and the largest number (as multiplying two negatives results in a positive product).\nThus, the result will be the maximum of these two products.\n\n# Approach\n1.Sort the Array: Sort the array to make it easier to select the largest and smallest numbers.\n2.Consider Two Cases:\n i)The product of the largest three numbers.\n ii)The product of the two smallest numbers and the largest number.\n3.Return the Maximum: Return the maximum of these two products.\n\n# Complexity\n- Time complexity:\n1.Sorting the array takes O(nlogn), where n is the number of elements in the array.\n2.Accessing the elements to compute the two possible products takes constant time, i.e., O(1).\nTherefore, the overall time complexity is O(nlogn).\n\n- Space complexity:\nThe space complexity is O(1) as we are only using a few variables for storing intermediate results, aside from the input array.\n\n# Code\n```java []\nclass Solution {\n public int maximumProduct(int[] nums) {\n Arrays.sort(nums);\n int n=nums.length;\n int a=nums[0]*nums[1]*nums[n-1];\n int b=nums[n-1]*nums[n-2]*nums[n-3];\n return Math.max(a,b);\n }\n} | 2 | 0 | ['Array', 'Math', 'Sorting', 'Java'] | 0 |
maximum-product-of-three-numbers | ayyo rama it was this :D | ayyo-rama-it-was-this-d-by-yesyesem-ef3e | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | yesyesem | NORMAL | 2024-09-16T05:00:15.838290+00:00 | 2024-09-16T05:00:15.838335+00:00 | 432 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maximumProduct(vector<int>& nums) {\n vector<int> pos;\n vector<int> neg;\n\n for(int i = 0; i < nums.size(); i++) {\n if(nums[i] < 0)\n neg.push_back(nums[i]);\n else \n pos.push_back(nums[i]);\n }\n\n sort(pos.begin(), pos.end(), greater<int>());\n sort(neg.begin(), neg.end());\n\n int maxProduct = INT_MIN;\n\n if (pos.size() >= 3) {\n maxProduct = max(maxProduct, pos[0] * pos[1] * pos[2]);\n }\n\n if (pos.size() >= 1 && neg.size() >= 2) {\n maxProduct = max(maxProduct, neg[0] * neg[1] * pos[0]);\n }\n\n if(neg.size()>=3&&pos.size()==0)\n {\n\n maxProduct=neg[neg.size()-1]*neg[neg.size()-2]*neg[neg.size()-3];\n }\n\n return maxProduct;\n }\n};\n\n``` | 2 | 0 | ['C++'] | 0 |
maximum-product-of-three-numbers | Simple Python Solution | simple-python-solution-by-started_coding-f945 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | started_coding_again | NORMAL | 2024-09-02T05:23:59.069684+00:00 | 2024-09-02T05:23:59.069709+00:00 | 249 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def maximumProduct(self, nums: List[int]) -> int:\n max1, max2, max3 = float(\'-inf\'), float(\'-inf\'), float(\'-inf\')\n min1, min2 = float(\'inf\'), float(\'inf\')\n\n for num in nums:\n if num > max1:\n max1, max2, max3 = num, max1, max2\n elif num > max2:\n max2, max3 = num, max2\n elif num > max3:\n max3 = num\n \n if num < min1:\n min1, min2 = num, min1\n elif num < min2:\n min2 = num\n \n return max(max1 * max2 * max3, max1 * min1 * min2)\n``` | 2 | 0 | ['Python3'] | 0 |
maximum-product-of-three-numbers | Without Sorting || Easy to UnderStand || 99% Beats | without-sorting-easy-to-understand-99-be-iaxa | Intuition\nBy maintaining the three largest and two smallest numbers while iterating through the array, we can compute the maximum product without sorting the a | tinku_tries | NORMAL | 2024-07-01T05:46:35.791200+00:00 | 2024-07-01T05:46:35.791223+00:00 | 1,683 | false | # Intuition\nBy maintaining the three largest and two smallest numbers while iterating through the array, we can compute the maximum product without sorting the array.\n\n# Approach\n1. **Initialize Variables:** Use variables to store the three largest and two smallest numbers.\n2. **Single Pass Through Array:** Update these variables as we iterate through the array.\n3. **Calculate the Maximum Product:** Use the stored values to calculate the maximum product of three numbers.\n\n# Complexity\n- **Time Complexity:** $$O(n)$$ because we only traverse the array once.\n- **Space Complexity:** $$O(1)$$ because we use a constant amount of extra space.\n\n# Code\nHere\'s the implementation of the above approach:\n\n```cpp\nclass Solution {\npublic:\n int maximumProduct(vector<int>& nums) {\n int max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN;\n int min1 = INT_MAX, min2 = INT_MAX;\n \n for (int num : nums) {\n // Update the three largest values\n if (num > max1) {\n max3 = max2;\n max2 = max1;\n max1 = num;\n } else if (num > max2) {\n max3 = max2;\n max2 = num;\n } else if (num > max3) {\n max3 = num;\n }\n \n // Update the two smallest values\n if (num < min1) {\n min2 = min1;\n min1 = num;\n } else if (num < min2) {\n min2 = num;\n }\n }\n \n // Maximum product is the maximum of the product of the three largest\n // numbers and the product of the two smallest numbers with the largest number.\n return max(max1 * max2 * max3, min1 * min2 * max1);\n }\n};\n```\n\n# Beats\n\n\n\n# Explanation\n- **Initialization:**\n - `max1`, `max2`, `max3` are initialized to `INT_MIN` to store the three largest numbers.\n - `min1`, `min2` are initialized to `INT_MAX` to store the two smallest numbers.\n- **Single Pass Through Array:**\n - Update `max1`, `max2`, `max3` if the current number is greater than any of these.\n - Update `min1`, `min2` if the current number is smaller than any of these.\n- **Calculate Maximum Product:** Return the maximum of the product of the three largest numbers and the product of the two smallest numbers with the largest number.\n\nThis solution efficiently finds the maximum product of three numbers in $$O(n)$$ time complexity. | 2 | 0 | ['Array', 'Math', 'C++'] | 1 |
maximum-product-of-three-numbers | Easy approach in C++ | easy-approach-in-c-by-shatakshi_sharma06-4mt8 | Intuition\nTo find maximum at first i thught just to find the max by sorting . ANd i did the same . But we have to check for an extra condition for -ve ones\n D | Shatakshi_Sharma06 | NORMAL | 2024-05-12T20:40:07.884002+00:00 | 2024-05-12T20:40:07.884032+00:00 | 870 | false | # Intuition\nTo find maximum at first i thught just to find the max by sorting . ANd i did the same . But we have to check for an extra condition for -ve ones\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nFirst sort the vector which will make it easy to iterate directly on indices.\nthen checking where the product of last three is maximum or product of first 2 and last 1 is maximum (In case of negatice number the smallest one will be at starting and after multiplying -ve we will get +ve)\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maximumProduct(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int product;\n int j=nums.size()-1;\n\n return max(nums[j]*nums[j-1]*nums[j-2] , nums[0]*nums[1]*nums[j]);\n \n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
maximum-product-of-three-numbers | 💯Java beginner friendly solution | java-beginner-friendly-solution-by-jeril-gxcf | Intuition\nThe intuition behind this approach is to sort the array in ascending order. Once the array is sorted, the maximum product can be achieved by either m | jeril-johnson | NORMAL | 2023-12-27T09:59:42.722060+00:00 | 2023-12-27T09:59:42.722092+00:00 | 903 | false | # Intuition\nThe intuition behind this approach is to sort the array in ascending order. Once the array is sorted, the maximum product can be achieved by either multiplying the three largest numbers or the two smallest and the largest number. By comparing both possibilities, the maximum product can be determined.\n\n# Approach\n1. Sort the array in ascending order.\n2. Calculate two possible products:\n - `a`: Product of the two smallest numbers and the largest number.\n - `b`: Product of the three largest numbers.\n3. Return the maximum of `a` and `b`.\n\n# Complexity\n- Time complexity: $$O(n \\log n)$$ - Sorting the array takes $$O(n \\log n)$$ time.\n- Space complexity: $$O(1)$$ - Constant space is used.\n\n# Code\n```java\nimport java.util.Arrays;\n\nclass Solution {\n public int maximumProduct(int[] nums) {\n Arrays.sort(nums);\n int n = nums.length - 1;\n int a = nums[0] * nums[1] * nums[n];\n int b = nums[n] * nums[n - 1] * nums[n - 2];\n return Math.max(a, b);\n }\n}\n``` | 2 | 0 | ['Java'] | 2 |
maximum-product-of-three-numbers | O(NlogN) ➡️O(N) ||Beats 100% || Two Java Approaches | onlogn-on-beats-100-two-java-approaches-co8b8 | Approach\nSort the array: so three max numbers are in the end of the array, two negative numbers whose product will be max will be on the start of the array.\n | Shivansu_7 | NORMAL | 2023-12-11T18:12:03.600780+00:00 | 2023-12-11T18:12:03.600813+00:00 | 894 | false | # Approach\n**Sort the array:** so three max numbers are in the end of the array, two negative numbers whose product will be max will be on the start of the array.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(N*logN)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maximumProduct(int[] nums) {\n Arrays.sort(nums);\n int case1 = nums[0]*nums[1]*nums[nums.length-1];\n int case2 = nums[nums.length-1]*nums[nums.length-2]*nums[nums.length-3];\n\n int maxProduct = Integer.max(case1, case2);\n return maxProduct;\n }\n}\n```\n# Approach\nFind max1, max2, max3, min1 and min2 using a for loop\n\n# Complexity\n- Time complexity: $$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\n public int maximumProduct(int[] nums) {\n int min1, min2, max1, max2, max3;\n min1 = min2 = Integer.MAX_VALUE;\n max1 = max2 = max3 = Integer.MIN_VALUE;\n for(int i = 0; i < nums.length; i++){\n //Updating maximums\n if(max1 < nums[i]){\n max3 = max2;\n max2 = max1;\n max1 = nums[i];\n }else if(max2 < nums[i]){\n max3 = max2;\n max2 = nums[i];\n }else if(max3 < nums[i]){\n max3 = nums[i];\n }\n \n //Updating minimums\n if(min1 > nums[i]){\n min2 = min1;\n min1 = nums[i];\n }else if(min2 > nums[i]){\n min2 = nums[i];\n }\n \n }\n \n return Math.max(max1 * max2 * max3 , min1 * min2 * max1);\n }\n``` | 2 | 0 | ['Java'] | 1 |
contain-virus | CPP DFS solution explained | cpp-dfs-solution-explained-by-rai02-znvl | I recently got this in an assessment. \n\nget clusters in every step. \n\ndeal with the largest clusters and expand all the other clusters.\n\nlets take the sam | rai02 | NORMAL | 2020-09-15T07:41:26.086341+00:00 | 2020-09-15T07:46:49.164203+00:00 | 6,978 | false | I recently got this in an assessment. \n\nget clusters in every step. \n\ndeal with the largest clusters and expand all the other clusters.\n\nlets take the sample case\n\n\n\n\n\n```\nclass cluster\n{\n public:\n set<pair<int,int>> c; // set of cells that are contaminated\n set<pair<int,int>> uc; // set of cells that are next to this cluster and are uncontaminated\n int wcnt = 0; // walls required to contain this structure \n \n};\nclass Solution {\npublic:\n \n void dfs(vector<vector<int>> &grid, int i, int j, vector<vector<bool>> &vis, cluster &cl)\n {\n if(i == grid.size() || i < 0 || j < 0 || j == grid[0].size()||vis[i][j]||grid[i][j] == -1)\n {\n // if the current src is out of grid bounds or if the cell is already visited or current cell is already walled that is -1\n return;\n }\n if(grid[i][j] == 0)\n {\n // if cell is uncontaminated then add to the uncontaminatd cells (uc) and increment wall cnt \n cl.wcnt++;\n cl.uc.insert({i,j});\n return;\n }\n // if current cell is contaminated add to contaminated and mark vis = true\n cl.c.insert({i,j});\n vis[i][j] = true;\n // call dfs in all directions\n dfs(grid,i+1,j,vis,cl); // above\n dfs(grid,i-1,j,vis,cl); // below\n dfs(grid,i,j+1,vis,cl); // right\n dfs(grid,i,j-1,vis,cl); // left\n \n }\n\n int containVirus(vector<vector<int>>& grid) {\n \n // row ka size\n int n = grid.size();\n // col ka size\n int m = grid[0].size();\n int ans = 0;\n while(1)\n {\n // visisted matrix\n vector<vector<bool>> vis(n,vector<bool>(m));\n // comparator for pq to sort it according to size of uncontaminated cells in cluster\n auto comp=[](const cluster& A,const cluster& B)\n { \n return A.uc.size()<B.uc.size();\n };\n // initialise priority queue\n priority_queue<cluster,vector<cluster>, decltype(comp)> pq(comp);\n // search for a contaminated cell in the grid\n for(int i = 0; i<n; i++)\n {\n for(int j = 0; j<m; j++)\n {\n if(!vis[i][j]&&grid[i][j] == 1)\n {\n // create a cluster\n cluster c;\n // call dfs\n dfs(grid,i,j,vis,c);\n pq.push(c);\n\n }\n }\n }\n // if size of priority queue is 0 the termination condition is reached ie all contaminated cells are contained.\n if(pq.size()==0)\n break;\n // get the biggest cluster is found make em all -1 and add the walls reqd to contain them \n cluster k = pq.top();\n pq.pop();\n for(auto x: k.c)\n {\n grid[x.first][x.second] = -1;\n }\n ans += k.wcnt;\n\n // for the rest of the clusters make their uncontaminated cells as contaminated\n while(!pq.empty())\n {\n cluster k1 = pq.top();\n pq.pop();\n for(auto x: k1.uc)\n {\n grid[x.first][x.second] = 1;\n } \n }\n \n }\n \n return ans;\n }\n};\n\n``` | 99 | 0 | ['Depth-First Search', 'C++'] | 15 |
contain-virus | Java, DFS, 9 ms, Explanation with comments | java-dfs-9-ms-explanation-with-comments-4ju0b | This class Region hold the information for each region.\n\nprivate class Region {\n // Using Set<Integer> instead of List<int[]> (int[] -> row and col pair), | gagarwal | NORMAL | 2020-03-02T18:57:36.239401+00:00 | 2020-03-05T03:59:50.153127+00:00 | 6,421 | false | This class **Region** hold the information for each region.\n```\nprivate class Region {\n // Using Set<Integer> instead of List<int[]> (int[] -> row and col pair),\n // as need to de-dupe the elements.\n // If N rows and M cols.\n // Total elements = NxM.\n // Given row and col calculate X as: X = row * M + col.\n // Given X calculate row and col as: row = X / M and col = X % M.\n\t\n // Infected nodes represented by 1.\n Set<Integer> infected = new HashSet<>();\n\n // Uninfected neighbors represented by 0 are the ones this region can infect if not contained.\n Set<Integer> uninfectedNeighbors = new HashSet<>();\n \n // Number of walls required to contain all the infected nodes (1s) in this region.\n // Note that two infected 1s can infect the same 0, so in this case we need two walls to save one 0 from two 1s.\n int wallsRequired = 0;\n}\n```\n\n**Steps**:\n1. Find all the regions.\n2. Get the region which has most number of uninfected neighbors. This region will cause maximum damage.\n3. For region in (2) contain the region. Mark all the infected nodes in this region as `2` to denote that these nodes are now contained and will not cause any more damage.\n4. For the remaining regions, expand by infecting the uninfected neighbors around these regions.\n5. Repeat steps (1) to (4) until there are no more regions with uninfected neighbors.\n\n```\npublic int containVirus(int[][] grid) {\n if (grid == null || grid.length == 0) {\n return 0;\n }\n\n int rows = grid.length;\n int cols = grid[0].length;\n\n int result = 0;\n\n while (true) {\n List<Region> regions = new ArrayList<>();\n\n // Find all the regions using DFS (or can also use BFS).\n boolean[][] visited = new boolean[rows][cols];\n for (int row = 0; row < rows; row++) {\n for (int col = 0; col < cols; col++) {\n if (grid[row][col] == 1 && !visited[row][col]) {\n Region region = new Region();\n dfs(grid, row, col, visited, region);\n\n // Add region to list of regions only if it can cause infection.\n if (region.uninfectedNeighbors.size() > 0) {\n regions.add(region);\n }\n }\n }\n }\n\n // No more regions that can cause further infection, we are done.\n if (regions.size() == 0) {\n break;\n }\n\n // Sort the regions. Region which can infected most neighbors first.\n regions.sort(new Comparator<Region>() {\n @Override\n public int compare(Region o1, Region o2) {\n return o2.uninfectedNeighbors.size() - o1.uninfectedNeighbors.size();\n }\n });\n\n // Build wall around region which can infect most neighbors.\n Region regionThatCauseMostInfection = regions.remove(0);\n result += regionThatCauseMostInfection.wallsRequired;\n\n for (int neighbor : regionThatCauseMostInfection.infected) {\n int row = neighbor / cols;\n int col = neighbor % cols;\n\n // Choosing 2 as to denote that this cell is now contained\n // and will not cause any more infection.\n grid[row][col] = 2;\n }\n\n // For remaining regions, expand (neighbors are now infected).\n for (Region region : regions) {\n for (int neighbor : region.uninfectedNeighbors) {\n int row = neighbor / cols;\n int col = neighbor % cols;\n grid[row][col] = 1;\n }\n }\n }\n\n return result;\n}\n\nprivate void dfs(int[][] grid, int row, int col, boolean[][] visited, Region region) {\n int rows = grid.length;\n int cols = grid[0].length;\n\n if (row < 0 || row >= rows || col < 0 || col >= cols || grid[row][col] == 2) {\n return;\n }\n\n if (grid[row][col] == 1) {\n // 1 is already infected.\n // Add to the list, since we are using Set it will be deduped if added multiple times.\n region.infected.add(row * cols + col);\n\n // If already visited, return as we do not want to go into infinite recursion.\n if (visited[row][col]) {\n return;\n }\n }\n\n visited[row][col] = true;\n\n if (grid[row][col] == 0) {\n // If 0 it is uninfected neighbor, we need a wall.\n // Remeber we can reach this 0 multiple times from different infected neighbors i.e. 1s,\n // and this will account for numbers of walls need to be built around this 0.\n region.wallsRequired++;\n\n // Add to uninfected list, it will be de-duped as we use Set.\n region.uninfectedNeighbors.add(row * cols + col);\n return;\n }\n\n // Visit neighbors.\n dfs(grid, row + 1, col, visited, region);\n dfs(grid, row - 1, col, visited, region);\n dfs(grid, row, col + 1, visited, region);\n dfs(grid, row, col - 1, visited, region);\n}\n``` | 45 | 0 | ['Depth-First Search', 'Java'] | 10 |
contain-virus | C++, DFS, 12ms | c-dfs-12ms-by-zestypanda-p90f | The solution simply models the process. \n1) Build walls = set those connected virus inactive, i.e. set as -1;\n2) Affected area != walls; For example, one 0 su | zestypanda | NORMAL | 2017-12-17T06:59:49.839000+00:00 | 2017-12-17T06:59:49.839000+00:00 | 5,633 | false | The solution simply models the process. \n1) Build walls = set those connected virus inactive, i.e. set as -1;\n2) Affected area != walls; For example, one 0 surrounded by all 1s have area = 1, but walls = 4.\n\nDFS\n```\nclass Solution {\npublic:\n int containVirus(vector<vector<int>>& grid) {\n int ans = 0;\n while (true) {\n int walls = process(grid);\n if (walls == 0) break; // No more walls to build\n ans += walls;\n }\n return ans;\n }\nprivate:\n int process(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n // cnt is max area to be affected by a single virus region; ans is corresponding walls\n int cnt = 0, ans = 0, color = -1, row = -1, col = -1;\n // visited virus as 1, visited 0 using different color to indicate being affected by different virus\n vector<vector<int>> visited(m, vector<int>(n, 0)); \n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1 && visited[i][j] == 0) {\n int walls = 0, area = dfs(grid, visited, i, j, color, walls);\n if (area > cnt) {\n ans = walls;\n cnt = area;\n row = i; \n col = j;\n }\n color--;\n }\n }\n }\n // set this virus region inactive\n buildWall(grid, row, col);\n // propagate other virus by 1 step\n visited = vector<vector<int>>(m, vector<int>(n, 0));\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1 && visited[i][j] == 0) \n spread(grid, visited, i, j);\n }\n }\n return ans;\n }\n int dfs(vector<vector<int>>& grid, vector<vector<int>>& visited, int row, int col, int color, int& walls) {\n int m = grid.size(), n = grid[0].size(), ans = 0;\n if (row < 0 || row >= m || col < 0 || col >= n) return 0;\n if (grid[row][col] == 0) {\n walls++; \n if (visited[row][col] == color) return 0;\n visited[row][col] = color;\n return 1;\n }\n // grid[row][col] could be -1, inactive virus\n if (visited[row][col] == 1 || grid[row][col] != 1) return 0; \n visited[row][col] = 1;\n vector<int> dir = {-1, 0, 1, 0, -1};\n for (int i = 0; i < 4; i++) \n ans += dfs(grid, visited, row+dir[i], col+dir[i+1], color, walls);\n return ans;\n }\n void buildWall(vector<vector<int>>& grid, int row, int col) {\n int m = grid.size(), n = grid[0].size();\n if (row < 0 || row >= m || col < 0 || col >= n || grid[row][col] != 1) return;\n grid[row][col] = -1; //set inactive\n vector<int> dir = {-1, 0, 1, 0, -1};\n for (int i = 0; i < 4; i++) \n buildWall(grid, row+dir[i], col+dir[i+1]);\n }\n void spread(vector<vector<int>>& grid, vector<vector<int>>& visited, int row, int col) {\n int m = grid.size(), n = grid[0].size();\n if (row < 0 || row >= m || col < 0 || col >= n || visited[row][col] == 1) return;\n if (grid[row][col] == 0) {\n grid[row][col] = 1;\n visited[row][col] = 1;\n }\n else if (grid[row][col] == 1) {\n visited[row][col] = 1;\n vector<int> dir = {-1, 0, 1, 0, -1};\n for (int i = 0; i < 4; i++) \n spread(grid, visited, row+dir[i], col+dir[i+1]);\n }\n }\n};\n```\n\nDFS, single pass with intermediate results saved, 19 ms\n```\nclass Solution {\npublic:\n int containVirus(vector<vector<int>>& grid) {\n int ans = 0;\n while (true) {\n int walls = model(grid);\n if (walls == 0) break;\n ans += walls;\n }\n return ans;\n }\nprivate:\n int model(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size(), N = 100;\n vector<unordered_set<int>> virus, toInfect;\n vector<vector<int>> visited(m, vector<int>(n, 0));\n vector<int> walls;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1 && visited[i][j] == 0) {\n virus.push_back(unordered_set<int>());\n toInfect.push_back(unordered_set<int>());\n walls.push_back(0);\n dfs(grid, visited, virus.back(), toInfect.back(), walls.back(), i, j);\n }\n }\n }\n int maxArea = 0, idx = -1;\n for (int i = 0; i < toInfect.size(); i++) {\n if (toInfect[i].size() > maxArea) {\n maxArea = toInfect[i].size();\n idx = i;\n }\n }\n if (idx == -1) return 0;\n for (int i = 0; i < toInfect.size(); i++) {\n if (i != idx) {\n for (int key : toInfect[i]) \n grid[key/N][key%N] = 1;\n }\n else {\n for (int key: virus[i]) \n grid[key/N][key%N] = -1;\n }\n }\n return walls[idx];\n }\nprivate:\n void dfs(vector<vector<int>>& grid, vector<vector<int>>& visited, unordered_set<int>& virus, unordered_set<int>& toInfect, int& wall, int row, int col) {\n int m = grid.size(), n = grid[0].size(), N = 100;\n if (row < 0 || row >= m || col < 0 || col >= n || visited[row][col] == 1) return;\n if (grid[row][col] == 1) {\n visited[row][col] = 1;\n virus.insert(row*N + col);\n vector<int> dir = {0, -1, 0, 1, 0};\n for (int i = 0; i < 4; i++)\n dfs(grid, visited, virus, toInfect, wall, row+dir[i], col+dir[i+1]);\n }\n else if (grid[row][col] == 0) {\n wall++;\n toInfect.insert(row*N + col);\n }\n }\n};\n``` | 17 | 0 | [] | 2 |
contain-virus | Contain the virus, contain the new coronavirus, fighting... | contain-the-virus-contain-the-new-corona-44ki | \n\ndef containVirus(self, grid: List[List[int]]) -> int:\n m=len(grid)\n n=len(grid[0])\n dirs=[(0,1),(1,0),(0,-1),(-1,0)]\n \n | foster2 | NORMAL | 2020-01-23T21:45:11.437462+00:00 | 2020-01-23T21:45:11.437498+00:00 | 1,998 | false | \n```\ndef containVirus(self, grid: List[List[int]]) -> int:\n m=len(grid)\n n=len(grid[0])\n dirs=[(0,1),(1,0),(0,-1),(-1,0)]\n \n def dfs(x,y,sn):\n if grid[x][y]==1:\n v[sn].add((x,y))\n seen.add((x,y))\n for dx,dy in dirs:\n nx=x+dx\n ny=y+dy\n if 0<=nx<m and 0<=ny<n: \n if grid[nx][ny]==0:\n f[sn].add((nx,ny))\n w[sn]+=1\n if grid[nx][ny]==1 and (nx,ny) not in v[sn]:\n v[sn].add((nx,ny))\n dfs(nx,ny,sn)\n \n res=0\n while True:\n v=collections.defaultdict(set) # infected area\n f=collections.defaultdict(set) # potential risk area\n w=collections.defaultdict(int) # walls in need\n seen=set()\n \n for i in range(m):\n for j in range(n):\n if grid[i][j]==1 and (i,j) not in seen:\n dfs(i,j,(i,j))\n \n if len(f)==0: \n break\n\n nnfrontiers = sorted(f,key=lambda x:len(f[x]),reverse=True)\n if len(nnfrontiers)>0:\n nnfrontier = nnfrontiers[0] \n res+=w[nnfrontier]\n\n for x,y in v[nnfrontier]: # get isolated\n grid[x][y]=2\n \n if len(nnfrontiers)>1: # spread the frontiers\n for i in range(1,len(nnfrontiers)):\n nnfrontier2 = nnfrontiers[i]\n for x,y in f[nnfrontier2]:\n grid[x][y]=1\n return res\n``` | 10 | 1 | [] | 0 |
contain-virus | Pyhon Easy Solution || DFS || Time O(m*n*max(m , n)) || Faster | pyhon-easy-solution-dfs-time-omnmaxm-n-f-enja | \n class Solution:\n def containVirus(self, mat: List[List[int]]) -> int:\n m,n = len(mat),len(mat[0])\n\n def dfs(i,j,visited,nextInfected): | Laxman_Singh_Saini | NORMAL | 2022-07-01T22:00:47.331524+00:00 | 2022-07-02T17:35:10.981765+00:00 | 2,117 | false | ```\n class Solution:\n def containVirus(self, mat: List[List[int]]) -> int:\n m,n = len(mat),len(mat[0])\n\n def dfs(i,j,visited,nextInfected): # return no. of walls require to quarantined dfs area\n if 0<=i<m and 0<=j<n and (i,j) not in visited:\n if mat[i][j]==2: # Already quarantined cell\n return 0\n if mat[i][j]==0:\n nextInfected.add((i,j)) # add cell which will be infected next day\n return 1 # require one wall to quarantined cell from one side\n \n else:\n visited.add((i,j))\n return dfs(i-1,j,visited,nextInfected) + dfs(i+1,j,visited,nextInfected) + dfs(i,j-1,visited,nextInfected) + dfs(i,j+1,visited,nextInfected) # traverse all four direction\n else:\n return 0\n\t\t\t\t\n ans = 0 \n while True: # this loop running "how many days we should installing the walls" times\n # For every day check which area infect more cells\n visited = set() # Using in dfs\n All_nextinfect = set()\n stop , walls = set(),0 # here stop store the indices of maximum no. of cells in which we stop spreading of virus this day\n \n for i in range(m):\n for j in range(n):\n if mat[i][j]==1 and (i,j) not in visited:\n nextInfected = set()\n a = dfs(i,j,visited,nextInfected)\n \n if len(stop)<len(nextInfected):\n All_nextinfect = All_nextinfect | stop # leave previous saved area from virus\n stop = nextInfected # pick new area which we want to save\n walls = a # require walls\n p,q = i,j # starting position(indices) of this area\n else:\n All_nextinfect = All_nextinfect | nextInfected \n \n if not stop : # if our job is done i.e. No cell will be infect Later\n break\n ans += walls # add new walls installed this day\n \n # change each cell value to 2 which will be covered by quarantined area\n def fun(p,q):\n if 0<=p<m and 0<=q<n and mat[p][q]==1:\n mat[p][q]=2\n fun(p+1,q)\n fun(p-1,q)\n fun(p,q-1)\n fun(p,q+1)\n fun(p,q) # start dfs from start point of quarantined area\n \n for a,b in All_nextinfect: # set new infected cell value = 1 for iterating next day\n mat[a][b] = 1\n\n return ans # Final answer \n```\t\t\n\t\t\n\t\t\n**if you like the solution : please Upvote :)**\n\t\t\n\t\t\n\t\t\n\t\t\n \n | 9 | 0 | ['Depth-First Search', 'Python', 'Python3'] | 1 |
contain-virus | C++ DFS simulation (20 ms) | c-dfs-simulation-20-ms-by-leetcode07-r1no | After each dfs, the matrix can contain only three types of numbers:\na) 1: infected cell\nb) 0: healthy cell\nc) 1e9: blocked cell\n\n2. If no cell becomes infe | leetcode07 | NORMAL | 2020-07-24T09:58:40.524242+00:00 | 2020-07-24T10:00:55.927496+00:00 | 1,763 | false | 1. After each dfs, the matrix can contain only three types of numbers:\na) 1: infected cell\nb) 0: healthy cell\nc) 1e9: blocked cell\n\n2. If no cell becomes infected the following night, the simulation breaks and returns answer\n\n3. The unordered set is used to find the total number of cells infected by a connected component the following night\n\n```\nclass Solution {\npublic:\n \n vector<vector<int> > g;\n int n, m, c, mx, w, r, ans, itr;\n unordered_set<int> s;\n \n int dfs(int i, int j){\n if(i<0 || i>=n || j<0 || j>=m || g[i][j]!=1)\n return 0;\n int ans=0;\n if(i+1<n && g[i+1][j]==0){\n s.insert((i+1)*m+j);\n ans++;\n }\n if(i-1>=0 && g[i-1][j]==0){\n s.insert((i-1)*m+j);\n ans++;\n }\n if(j+1<m && g[i][j+1]==0){\n s.insert(i*m+(j+1));\n ans++;\n }\n if(j-1>=0 && g[i][j-1]==0){\n s.insert(i*m+(j-1));\n ans++;\n }\n g[i][j]=c;\n ans+=dfs(i+1, j);\n ans+=dfs(i-1, j);\n ans+=dfs(i, j+1);\n ans+=dfs(i, j-1);\n return ans; // total number of walls needed to block this connected component\n }\n \n int containVirus(vector<vector<int>>& grid) {\n g=grid, n=g.size(), m=g[0].size(), ans=0;\n while(true){\n c=2, mx=0;\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(g[i][j]==1){\n s.clear();\n int walls=dfs(i, j);\n if(mx<s.size()){\n mx=s.size();\n w=walls;\n r=c;\n }\n c++;\n }\n }\n }\n if(mx==0)\n break;\n ans+=w;\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(g[i][j]==r)\n g[i][j]=1e9;\n else if(g[i][j]>1 && g[i][j]!=1e9){\n g[i][j]=1;\n if(i+1<n && !g[i+1][j]) g[i+1][j]=1;\n if(i-1>=0 && !g[i-1][j]) g[i-1][j]=1;\n if(j+1<m && !g[i][j+1]) g[i][j+1]=1;\n if(j-1>=0 && !g[i][j-1]) g[i][j-1]=1;\n }\n }\n }\n }\n return ans;\n }\n};\n``` | 7 | 0 | [] | 0 |
contain-virus | Commented Python using DFS with explanation | commented-python-using-dfs-with-explanat-qbe4 | Find most threatening region (would infect most normal cells next night) via DFS and at same time count the walls needed to wall off, and return it\'s coordinat | fortuna911 | NORMAL | 2019-02-02T20:23:22.865630+00:00 | 2019-02-02T20:23:22.865693+00:00 | 1,015 | false | 1. Find most threatening region (would infect most normal cells next night) via DFS and at same time count the walls needed to wall off, and return it\'s coordinates\n2. Quarantine that region by doing DFS and walling that region off by setting 1\'s to -1\'s\n3. Simulate night virus spread: find a \'1\' do a DFS on it and set perimeter empty spaces to 2. Once done this for all cells, set 2\'s to 1. This is so that while iterating it doesn\'t see newly infected cells as cells next to the empty perimeter (then it would spread all in one night)\n\nRT: O(M*N * infected_regions)\nSpc: O(M*N) (could be a deep DFS)\n\n```\n def containVirus(self, grid):\n dirs = [(0, 1), (1, 0), (-1, 0), (0, -1)]\n\n def cells():\n for r in range(R):\n for c in range(C):\n yield (r, c)\n\n def is_valid(i, j):\n return 0 <= i < R and 0 <= j < C\n\n def neighbours(r, c):\n """Get valid neighbour cells"""\n for dr, dc in dirs:\n if is_valid(r+dr, c+dc):\n yield (r+dr, c+dc)\n\n def pick_most_threatening_region():\n visited = set()\n\n def dfs(r, c):\n """Returns number of walls needed to quarantine infected region\n starting at (r,c)"""\n # Avoid already visited or quarantined cells.\n if (r, c) in visited or grid[r][c] == -1:\n return 0\n # Found an empty perimeter space\n if grid[r][c] == 0:\n perimeter.add((r, c))\n # Counts as one wall needed to contain infected cell.\n return 1\n \n visited.add((r, c))\n # Explore neighbours and return the sum of the walls needed to\n # contain their perimeter.\n return sum(dfs(nr, nc) for (nr, nc) in neighbours(r, c))\n\n max_perimeter, max_p_walls, max_start = 0, 0, (0, 0)\n for r, c in cells():\n # Find cells that have not yet been visited and are infected.\n if (r, c) not in visited and grid[r][c] == 1:\n perimeter = set()\n # Get the total walls needed to quarantine the infected region.\n walls = dfs(r, c)\n # If the parameter we could save is the biggest we\'ve seen...\n if len(perimeter) > max_perimeter:\n # update the walls needed to quarantine, and an infected cell\n # from which we might mark the infected region as quarantined (setting -1)\n max_perimeter, max_p_walls, max_start = len(perimeter), walls, (r, c)\n return max_p_walls, max_start\n\n def quarantine(r, c):\n """Mark an infected region as quarantined by setting cells to -1"""\n grid[r][c] = -1\n # Explore neighbours to quarantine them too.\n for nr, nc in neighbours(r, c):\n if grid[nr][nc] == 1:\n quarantine(nr, nc)\n \n def simulate_night():\n """Spreads the infection by one night of non-quarntined regions."""\n \n def infected_neighbour(r, c):\n """Returns True if an orthogonally adjacent square is infected."""\n return any(grid[nr][nc] == 1 for nr, nc in neighbours(r, c))\n \n for r, c in cells():\n # Find clean cells that are next to infected cells\n if grid[r][c] == 0 and infected_neighbour(r, c):\n # Set them temporarily to 2, so that further iterations do not\n # count them as infected (otherwise it would spread endlessly\n # in one night).\n grid[r][c] = 2\n \n # Go over a second time and set the temporarily marked newly infected cells\n # to permanently infected.\n for r, c in cells():\n if grid[r][c] == 2:\n grid[r][c] = 1\n\n if not grid or not grid[0]:\n return 0\n R, C = len(grid), len(grid[0])\n\n walls = 0\n while True:\n new_walls, (r, c) = pick_most_threatening_region()\n # Stop when there are no more infected regions, i.e. only\n # -1 (quarantined by us) and 0\'s are left.\n if new_walls == 0:\n return walls\n quarantine(r, c)\n walls += new_walls\n simulate_night()\n return walls\n``` | 7 | 0 | [] | 0 |
contain-virus | [Contian Virus] Do I misunstand something? | contian-virus-do-i-misunstand-something-mocz6 | For input \n[[0,1,0,1,1,1,1,1,1,0],\n[0,0,0,1,0,0,0,0,0,0],\n[0,0,1,1,1,0,0,0,1,0],\n[0,0,0,1,1,0,0,1,1,0],\n[0,1,0,0,1,0,1,1,0,1],\n[0,0,0,1,0,1,0,1,1,1],\n[0, | arnoldlee | NORMAL | 2018-01-06T21:59:25.283000+00:00 | 2018-01-06T21:59:25.283000+00:00 | 1,409 | false | For input \n[[0,1,0,1,1,1,1,1,1,0],\n[0,0,0,1,0,0,0,0,0,0],\n[0,0,1,1,1,0,0,0,1,0],\n[0,0,0,1,1,0,0,1,1,0],\n[0,1,0,0,1,0,1,1,0,1],\n[0,0,0,1,0,1,0,1,1,1],\n[0,1,0,0,1,0,0,1,1,0],\n[0,1,0,1,0,0,0,1,1,0],\n[0,1,1,0,0,1,1,0,0,1],\n[1,0,1,1,0,1,0,1,0,1]]\nMy solution gives answer=40 but the answer=38. \nI calculated manually, first all we should contain the infected area in the right(I change it to 2), and we need 22 walls;\n\t\t{ 0, 1, 0, 1, 1, 1, 1, 1, 1, 0 },\n\t\t{ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },\n\t\t{ 0, 0, 1, 1, 1, 0, 0, 0, 2, 0 }, // 3 walls\n\t\t{ 0, 0, 0, 1, 1, 0, 0, 2, 2, 0 }, // 2 walls, 2 walls\n\t\t{ 0, 1, 0, 0, 1, 0, 2, 2, 0, 2 }, // 3 walls, 1 walls, 2 walls\n\t\t{ 0, 0, 0, 1, 0, 1, 0, 2, 2, 2 }, // 1 walls, 1 walls, 1 walls\n\t\t{ 0, 1, 0, 0, 1, 0, 0, 2, 2, 0 }, // 1 walls, 1 walls\n\t\t{ 0, 1, 0, 1, 0, 0, 0, 2, 2, 0 }, // 2 walls, 2 walls\n\t\t{ 0, 1, 1, 0, 0, 1, 1, 0, 0, 1 },\n\t\t{ 1, 0, 1, 1, 0, 1, 0, 1, 0, 1 };\nafter one day, it will be like this (* is newly affected cells)\n\t\t{ *, 1, *, 1, 1, 1, 1, 1, 1, * },\n\t\t{ 0, *, *, 1, *, *, *, *, *, 0 }, \n\t\t{ 0, *, 1, 1, 1, *, 0, 0, 2, 0 }, \n\t\t{ 0, *, *, 1, 1, *, 0, 2, 2, 0 },\n\t\t{ *, 1, *, *, 1, *, 2, 2, 0, 2 },\n\t\t{ 0, *, *, 1, *, 1, *, 2, 2, 2 },\n\t\t{ *, 1, *, *, 1, *, 0, 2, 2, 0 },\n\t\t{ *, 1, *, 1, *, *, *, 2, 2, * },\n\t\t{ *, 1, 1, *, *, 1, 1, *, *, 1 },\n\t\t{ 1, *, 1, 1, *, 1, *, 1, *, 1 };\nand we need 18 walls to protect unaffected cells. Could any one tell me what is wrong with my answer? Do I misunderstand something?\n\nAny comments are welcome! | 7 | 0 | [] | 2 |
contain-virus | A Visualization Tool | a-visualization-tool-by-rowe1227-64cq | This is a tricky problem to debug, however visualizing the spread of the virus helps.\nHere is a visualization tool that shows how the grid changes each day.\n1 | rowe1227 | NORMAL | 2020-11-10T21:26:00.760663+00:00 | 2020-11-10T22:21:56.783135+00:00 | 835 | false | This is a tricky problem to debug, however visualizing the spread of the virus helps.\nHere is a visualization tool that shows how the grid changes each day.\n1 means the cell is infected and 2 means the cell has been contained with walls.\nHere is an example output with a few notes added:\n\n```html5\n<b>Grid status on day 0: Virus has not begun to spread.</b>\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, <b>1</b>, 0, 0]\n[<b>1</b>, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, <b>1</b>, 0, 0, 0, <b>1</b>, 0, 0, 0] #\n[0, 0, 0, 0, 0, 0, <b>1</b>, 0, 0, 0] # Notice this group of 1s will be walled first and will not spread\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, <b>1</b>, 0]\n[0, 0, 0, 0, <b>1</b>, 0, <b>1</b>, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n```\n```html5\n<b>Grid status on day 1</b>\n[0, 0, 0, 0, 0, 0, 0, <b>1</b>, 0, 0]\n[<b>1</b>, 0, 0, 0, 0, 0, <b>1</b>, <b>1</b>, <b>1</b>, 0]\n[<b>1</b>, <b>1</b>, <b>1</b>, 0, 0, 0, 0, <b>1</b>, 0, 0]\n[<b>1</b>, <b>1</b>, <b>1</b>, <b>1</b>, 0, 0, <b>2</b>, 0, 0, 0] #\n[0, 0, <b>1</b>, 0, 0, 0, <b>2</b>, 0, 0, 0] # 2 Means the group of infected nodes has been contained\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, <b>1</b>, 0] #\n[0, 0, 0, 0, <b>1</b>, 0, <b>1</b>, <b>1</b>, <b>1</b>, <b>1</b>] #\n[0, 0, 0, <b>1</b>, <b>1</b>, <b>1</b>, <b>1</b>, <b>1</b>, <b>1</b>, 0] # Three groups of 1s have merged into one large group of 1s.\n[0, 0, 0, 0, <b>1</b>, 0, <b>1</b>, 0, 0, 0] #\n```\n```html5\n<b>Grid status on day 2</b>\n[<b>1</b>, 0, 0, 0, 0, 0, <b>1</b>, <b>1</b>, <b>1</b>, 0] #\n[<b>1</b>, <b>1</b>, <b>1</b>, 0, 0, <b>1</b>, <b>1</b>, <b>1</b>, <b>1</b>, <b>1</b>] # These two groups will not merge\n[<b>1</b>, <b>1</b>, <b>1</b>, <b>1</b>, 0, 0, <b>1</b>, <b>1</b>, <b>1</b>, 0] # because one of them {(3,6), (4,6)} is walled off\n[<b>1</b>, <b>1</b>, <b>1</b>, <b>1</b>, <b>1</b>, 0, <b>2</b>, <b>1</b>, 0, 0] #\n[<b>1</b>, <b>1</b>, <b>1</b>, <b>1</b>, 0, 0, <b>2</b>, 0, 0, 0] #\n[0, 0, <b>1</b>, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, <b>2</b>, 0]\n[0, 0, 0, 0, <b>2</b>, 0, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>]\n[0, 0, 0, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, 0]\n[0, 0, 0, 0, <b>2</b>, 0, <b>2</b>, 0, 0, 0]\n```\n```html5\n<b>Grid status on day 3</b>\n[<b>2</b>, 0, 0, 0, 0, <b>1</b>, <b>1</b>, <b>1</b>, <b>1</b>, <b>1</b>]\n[<b>2</b>, <b>2</b>, <b>2</b>, 0, <b>1</b>, <b>1</b>, <b>1</b>, <b>1</b>, <b>1</b>, <b>1</b>]\n[<b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, 0, <b>1</b>, <b>1</b>, <b>1</b>, <b>1</b>, <b>1</b>]\n[<b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, 0, <b>2</b>, <b>1</b>, <b>1</b>, 0]\n[<b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, 0, 0, <b>2</b>, <b>1</b>, 0, 0]\n[0, 0, <b>2</b>, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, <b>2</b>, 0]\n[0, 0, 0, 0, <b>2</b>, 0, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>]\n[0, 0, 0, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, 0]\n[0, 0, 0, 0, <b>2</b>, 0, <b>2</b>, 0, 0, 0]\n```\n```html5\n<b>Grid status on day 4: Virus fully contained. No growth between day 3 and day 4.</b>\n[<b>2</b>, 0, 0, 0, 0, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>]\n[<b>2</b>, <b>2</b>, <b>2</b>, 0, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>]\n[<b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, 0, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>]\n[<b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, 0, <b>2</b>, <b>2</b>, <b>2</b>, 0]\n[<b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, 0, 0, <b>2</b>, <b>2</b>, 0, 0]\n[0, 0, <b>2</b>, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, <b>2</b>, 0]\n[0, 0, 0, 0, <b>2</b>, 0, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>]\n[0, 0, 0, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, <b>2</b>, 0]\n[0, 0, 0, 0, <b>2</b>, 0, <b>2</b>, 0, 0, 0]\n```\n\n<br>\n\nTo print a day by day visualization of the virus spread, run the following **Python3** code with a test-case of your choice as the input:\n\n<br>\n\n```python\nclass Group_By_ID(object):\n def __init__(self, arr = [[]], walls = set(), day = 0, contained = set()):\n self.group_id = 0\n self.group = {}\n self.node_id = {}\n self.arr = arr\n self.walls = walls\n self.quarantine_not_complete = True\n self.day = day\n self.contained = contained\n self.step()\n self.show()\n \n def step(self) -> None:\n \'\'\'Identifies groups of infected nodes. Places a wall around the most dangerous group. Spreads the virus by 1 step.\'\'\'\n self.get_edges()\n self.group_infections()\n self.wall_dangerous_group()\n self.spread_virus()\n \n def show(self) -> None:\n \'\'\'Prints the current status of the array.\'\'\'\n print(\'\\nGrid status on day {}\'.format(self.day))\n for r in range(len(self.arr)):\n print([2 if (r,c) in self.contained else self.arr[r][c] for c in range(len(self.arr[0]))])\n \n def get_edges(self) -> None:\n \'\'\'Identifies infected_edges between two infected nodes and other_edges that have at least one un-infected node.\'\'\'\n self.infected_edges = set()\n self.other_edges = set()\n R, C = len(self.arr), len(self.arr[0])\n for r in range(R):\n for c in range(C):\n for i, j in ((r,c),(r+1,c),(r-1,c),(r,c+1),(r,c-1)):\n if (0 <= i < R) and (0 <= j < C):\n edge = ((r, c), (i, j))\n if edge not in self.walls:\n self.infected_edges.add(edge) if self.arr[i][j] == self.arr[r][c] == 1 else self.other_edges.add(edge)\n \n def group_infections(self) -> None:\n \'\'\'Collects infected edges into groups where each group consists of connected infected nodes.\'\'\'\n for a, b in self.infected_edges:\n self.union(a, b)\n \n def union(self, a, b) -> None:\n \'\'\'Connects infected nodes a and b. Updates the infected groups to reflect the new connection.\'\'\'\n if (a in self.node_id) and (b in self.node_id) and (self.node_id[a] != self.node_id[b]):\n self.merge_groups(a, b)\n elif (a in self.node_id) or (b in self.node_id):\n self.insert_node(a, b)\n else:\n self.create_new_group(a, b)\n \n def merge_groups(self, a, b) -> None:\n \'\'\'Both a and b belong to a group. Merge the smaller group into the larger group.\'\'\'\n obsolete_id, target_id = sorted((self.node_id[a], self.node_id[b]), key = lambda id: len(self.group[id]))\n for node in self.group[obsolete_id]:\n self.node_id[node] = target_id\n self.group[target_id] |= self.group[obsolete_id]\n del self.group[obsolete_id]\n \n def insert_node(self, a, b) -> None:\n \'\'\'Only a or only b belongs to a group, add the new node to the existing group.\'\'\'\n a, b = (a, b) if a in self.node_id else (b, a)\n target_id = self.node_id[a]\n self.node_id[b] = target_id\n self.group[target_id] |= set([b])\n \n def create_new_group(self, a, b) -> None:\n \'\'\'Node a and node b do not belong to a group, create a new group {a, b}.\'\'\'\n self.group[self.group_id] = set([a,b])\n self.node_id[a] = self.node_id[b] = self.group_id\n self.group_id += 1\n \n def wall_dangerous_group(self) -> int:\n \'\'\'Identifies the most dangerous group and places a wall around it.\'\'\'\n most_infected_nodes = set()\n new_walls = set()\n new_contain = -1\n R, C = len(self.arr), len(self.arr[0])\n for g in self.group:\n projected_infected_nodes = set()\n projected_infected_edges = set()\n for r, c in self.group[g]:\n for i, j in ((r+1,c),(r-1,c),(r,c+1),(r,c-1)):\n if (0 <= i < R) and (0 <= j < C):\n edge = ((r, c), (i, j))\n if (edge in self.other_edges) and (edge not in self.walls):\n projected_infected_edges.add(edge)\n projected_infected_edges.add(edge[::-1])\n projected_infected_nodes.add((i, j))\n if len(projected_infected_nodes) > len(most_infected_nodes):\n most_infected_nodes = projected_infected_nodes.copy()\n new_walls = projected_infected_edges.copy()\n new_contain = g\n \n if new_contain != -1: self.contained |= self.group[new_contain]\n self.walls |= new_walls\n self.quarantine_not_complete = True if new_walls else False\n \n def spread_virus(self) -> None:\n \'\'\'Spreads virus by one step\'\'\'\n R, C = len(self.arr), len(self.arr[0])\n for g in self.group:\n for r, c in self.group[g]:\n for i, j in ((r+1,c),(r-1,c),(r,c+1),(r,c-1)):\n if (0 <= i < R) and (0 <= j < C):\n edge = ((r,c),(i,j))\n if edge not in self.walls:\n self.arr[i][j] = 1\n \n def __repr__(self):\n \'\'\'Returns a dictionary of class attributes that represents the current state of the class instance.\'\'\'\n return {\'arr\': [row[:] for row in self.arr],\n \'walls\': self.walls.copy(),\n \'day\': self.day + 1,\n \'contained\': self.contained.copy()}\n \nclass Solution:\n def containVirus(self, arr: List[List[int]]) -> int:\n print(\'Grid status on day 0\')\n for row in arr: print(row)\n \n sol = Group_By_ID(arr = arr, walls = set(), day = 1, contained = set())\n while sol.quarantine_not_complete:\n sol = Group_By_ID(**sol.__repr__())\n return len(sol.walls) // 2\n``` | 5 | 0 | [] | 0 |
contain-virus | Concise c++ solution with BFS, 12ms | concise-c-solution-with-bfs-12ms-by-mzch-k0f0 | \nint containVirus(vector<vector<int>>& g) {\n int res = 0, c = 1; // c increments for visited cells\n\n while (true) {\n // tuple components: wall | mzchen | NORMAL | 2017-12-17T09:49:04.129000+00:00 | 2018-08-10T22:13:23.899539+00:00 | 2,108 | false | ```\nint containVirus(vector<vector<int>>& g) {\n int res = 0, c = 1; // c increments for visited cells\n\n while (true) {\n // tuple components: walls, inside coords with value c, border coords with value 0\n vector<tuple<int, vector<pair<int, int>>, set<pair<int, int>>>> areas;\n int mx = 0, idx;\n\n for (int i = 0; i < g.size(); i++) {\n for (int j = 0; j < g[0].size(); j++) {\n if (g[i][j] == c) {\n areas.resize(areas.size() + 1); // found a new area\n\n int &walls = get<0>(areas.back());\n auto &inside = get<1>(areas.back());\n auto &border = get<2>(areas.back());\n\n g[i][j] = c + 1; // mark as visited\n inside.emplace_back(i, j);\n\n queue<pair<int, int>> q;\n q.emplace(i, j);\n\n while (!q.empty()) {\n int x, y;\n tie(x, y) = q.front();\n q.pop();\n\n for_4neighbors(g, x, y, [&](int a, int b) {\n if (g[a][b] == c) {\n q.emplace(a, b);\n g[a][b] = c + 1; // mark as visited\n inside.emplace_back(a, b);\n } else if (g[a][b] == 0) {\n border.emplace(a, b);\n walls++;\n }\n });\n }\n\n if (border.size() > mx) {\n mx = border.size();\n idx = areas.size() - 1;\n }\n }\n }\n }\n\n if (mx == 0) break;\n c++; // all visited viruses are back\n\n for (auto &p : get<1>(areas[idx]))\n g[p.first][p.second] = -1; // mark as dead\n get<2>(areas[idx]).clear(); // dead viruses no longer spread\n\n for (auto &a : areas)\n for (auto &p : get<2>(a))\n g[p.first][p.second] = c; // mark as contaminated\n\n res += get<0>(areas[idx]);\n }\n\n return res;\n}\n```\n\nWith a helper defined:\n```\ntemplate<typename Ctnr, typename Func>\ninline void for_4neighbors(const Ctnr &ctnr, int row, int col, Func func) {\n if (row - 1 >= 0)\n func(row - 1, col);\n if (row + 1 < ctnr.size())\n func(row + 1, col);\n if (col - 1 >= 0)\n func(row, col - 1);\n if (col + 1 < ctnr[0].size())\n func(row, col + 1);\n}\n``` | 5 | 0 | [] | 1 |
contain-virus | My Neat Java Solution Using Dfs | my-neat-java-solution-using-dfs-by-llz01-hbv8 | \nclass Solution {\n public int containVirus(int[][] grid) {\n int[] cost = new int[]{0};\n while(check(grid, cost));\n return cost[0];\ | llz0108 | NORMAL | 2017-12-20T01:29:53.196000+00:00 | 2018-10-10T16:06:09.957671+00:00 | 2,617 | false | ```\nclass Solution {\n public int containVirus(int[][] grid) {\n int[] cost = new int[]{0};\n while(check(grid, cost));\n return cost[0];\n }\n \n private boolean check(int[][] grid, int[] cost) {\n// update every day information and return false if no improvement can be made\n int count = 1;\n int max = -1;\n boolean flag = false;\n List<int[]> info = new ArrayList<>();\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid[0].length; j++) {\n if (grid[i][j] == 1) {\n count++;\n int[][] walls = new int[grid.length][grid[0].length];\n int[] res = new int[2];\n grid[i][j] = count;\n dfs(i, j, grid, count, walls, res);\n if (res[0] != 0) flag = true;\n if (max == -1 || res[0] > info.get(max)[0]) {\n max = count - 2;\n }\n info.add(res);\n }\n }\n }\n if (count == 1) {\n return false;\n }\n cost[0] += info.get(max)[1];\n update(grid, max + 2);\n return flag;\n }\n \n \n private void dfs(int row, int col, int[][] grid, int count, int[][] walls, int[] res) {\n//dfs and record number of walls need to block this area and how many 0s are under infection\n int[] shiftX = new int[]{1, 0, -1, 0};\n int[] shiftY = new int[]{0, 1, 0, -1};\n \n for(int i = 0; i < 4; i++) {\n int newRow = row + shiftX[i];\n int newCol = col + shiftY[i];\n if (newRow >= 0 && newRow < grid.length && newCol >= 0 && newCol < grid[0].length) {\n if (grid[newRow][newCol] == 1) {\n grid[newRow][newCol] = count;\n dfs(newRow, newCol, grid, count, walls, res);\n } else if (grid[newRow][newCol] == 0) {\n if (walls[newRow][newCol] == 0) res[0]++;\n if ((walls[newRow][newCol] & 1 << i) == 0) {\n res[1]++;\n walls[newRow][newCol] |= 1 << i;\n }\n }\n }\n }\n }\n \n \n private void update(int[][] grid, int quarantine) {\n//set the new infected area and set blocked area to be -1\n int[] shiftX = new int[]{1, 0, -1, 0};\n int[] shiftY = new int[]{0, 1, 0, -1};\n \n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid[0].length; j++) {\n if (grid[i][j] > 1 && grid[i][j] != quarantine) {\n for (int k = 0; k < 4; k++) {\n int newRow = i + shiftX[k];\n int newCol = j + shiftY[k];\n if (newRow >= 0 && newRow < grid.length && newCol >= 0 && newCol < grid[0].length && grid[newRow][newCol] == 0) {\n grid[newRow][newCol] = 1;\n }\n }\n grid[i][j] = 1;\n } else if (grid[i][j] == quarantine) {\n grid[i][j] = -1;\n }\n }\n }\n } \n}\n``` | 5 | 0 | [] | 3 |
contain-virus | c++ | Exactly what the hint said | c-exactly-what-the-hint-said-by-shourabh-bvns | Algorithm\n1. Iterate over all regions and get the coordinates of region with maximum area threatened\n2. Mark the max threatened region obtained in step 1 as - | shourabhpayal | NORMAL | 2021-06-23T09:28:36.029737+00:00 | 2021-06-23T09:28:57.270208+00:00 | 1,092 | false | **Algorithm**\n1. Iterate over all regions and get the coordinates of region with maximum area threatened\n2. Mark the max threatened region obtained in step 1 as -1 signifying it is disinfected. Add perimeter to answer.\n3. Expand the remaining regions\n4. Repeat step 1 to 3 till max area threatened = 0\n\n***Note:*** \n* For area threatened calculation we cannot repeat the 0 cells adjoining the region therefore we use visited set\n* For perimeter calculation we don\'t have such restrictions\n* For both of the above cases we cannot goto a cell marked -1 which signifies as disinfected\n\n**Code**\n```\nclass Solution {\npublic:\n int m, n;\n int ans = 0;\n \n // -1 means disinfected\n int color = 2;\n \n // for perimeter calculation we cannot go to cells marked -1 but we can goto all other cells\n int perimeter = 0;\n \n // we can go to cells marked as 0 only\n // this will store the area being threatened\n int areat = 0;\n \n int containVirus(vector<vector<int>>& a) {\n m = a.size();\n n = a[0].size();\n\n while(1){\n int restrictX, restrictY;\n int big = -1;\n for(int i = 0 ; i < m ; i++){\n for(int j = 0 ; j < n ; j++){\n if(a[i][j] == color-1){\n \n //capture this region and color it with color\n dfs(a, i, j);\n areat = 0;\n set<pair<int, int>> visited;\n calculateAreat(a, i, j, visited);\n //calculateAreat marks the region with -2 so we will restore\n restore(a, i, j);\n if(big < areat){\n big = areat;\n restrictX = i;\n restrictY = j;\n }\n }\n }\n }\n \n if(big != -1){\n perimeter = 0;\n calculatePerimeter(a, restrictX, restrictY);\n ans += perimeter;\n int temp = color;\n color = -1;\n // disinfect this region by marking as -1\n restore(a, restrictX, restrictY);\n \n color = temp+1;\n for(int i = 0 ; i < m ; i++){\n for(int j = 0 ; j < n ; j++){\n if(a[i][j] == color-1){\n expand(a, i, j, a[i][j]);\n // expand marks the region as -2 so we restore it to color\n restore(a, i, j);\n }\n }\n }\n color++;\n }\n else{\n break;\n }\n }\n \n return ans;\n }\n \n void expand(vector<vector<int>>& a, int x, int y, int currcolor){\n if(x < 0 || y < 0 || x >= m || y >= n){\n return;\n }\n \n if(a[x][y] == 0){\n a[x][y] = -2;\n return;\n }\n \n if(a[x][y] == -2 || a[x][y] == -1 || a[x][y] != currcolor){\n return;\n }\n \n a[x][y] = -2;\n expand(a, x+1, y, currcolor);\n expand(a, x, y+1, currcolor);\n expand(a, x, y-1, currcolor);\n expand(a, x-1, y, currcolor);\n }\n \n void dfs(vector<vector<int>>& a, int x, int y){\n if(x < 0 || y < 0 || x >= m || y >= n || a[x][y] == 0 || a[x][y] == -1){\n return;\n }\n \n if(a[x][y] == color){\n return;\n }\n \n a[x][y] = color;\n dfs(a, x+1, y);\n dfs(a, x, y+1);\n dfs(a, x, y-1);\n dfs(a, x-1, y);\n }\n \n void restore(vector<vector<int>>& a, int x, int y){\n if(x < 0 || y < 0 || x >= m || y >= n || a[x][y] == 0 || a[x][y] != -2){\n return;\n }\n \n a[x][y] = color;\n restore(a, x+1, y);\n restore(a, x, y+1);\n restore(a, x, y-1);\n restore(a, x-1, y);\n }\n \n // -2 is under processing\n void calculatePerimeter(vector<vector<int>>& a, int x, int y){\n if(x < 0 || y < 0 || x >= m || y >= n || a[x][y] == -1 || a[x][y] == -2){\n return;\n }\n \n if(a[x][y] == 0){\n perimeter++;\n return;\n }\n \n a[x][y] = -2;\n calculatePerimeter(a, x+1, y);\n calculatePerimeter(a, x, y+1);\n calculatePerimeter(a, x, y-1);\n calculatePerimeter(a, x-1, y);\n }\n \n // -2 is under processing\n void calculateAreat(vector<vector<int>>& a, int x, int y, set<pair<int, int>> &visited){\n if(x < 0 || y < 0 || x >= m || y >= n || a[x][y] == -2 \n || a[x][y] == -1 || visited.count({x,y})){\n return;\n }\n \n if(a[x][y] == 0){\n visited.insert({x,y});\n areat++;\n return;\n }\n \n a[x][y] = -2;\n calculateAreat(a, x+1, y, visited);\n calculateAreat(a, x, y+1, visited);\n calculateAreat(a, x, y-1, visited);\n calculateAreat(a, x-1, y, visited);\n }\n \n void print(vector<vector<int>> &a){\n for(int i = 0 ; i < m ; i++){\n for(int j = 0 ; j < n ; j++){\n cout<<a[i][j]<<"\\t";\n }\n cout<<endl;\n }\n cout<<endl;\n }\n};\n``` | 4 | 0 | ['Depth-First Search', 'C'] | 0 |
contain-virus | 749: Solution with step by step explanation | 749-solution-with-step-by-step-explanati-44vj | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n\nm, n = len(mat), len(mat[0])\nDIRECTIONS = [(-1, 0), (1, 0), (0, -1), ( | Marlen09 | NORMAL | 2023-10-22T17:43:33.600875+00:00 | 2023-10-22T17:43:33.600907+00:00 | 532 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\nm, n = len(mat), len(mat[0])\nDIRECTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n```\nm and n capture the dimensions of the matrix.\nDIRECTIONS is a list of four possible moves from a cell: up, down, left, and right.\n\n```\ndef dfs(i, j, visited):\n```\n\nThis function explores an infected region starting from cell (i, j) and computes:\n\nThe set of uninfected cells that can be infected by this region.\nThe number of walls needed to quarantine this region.\nThe function uses a DFS strategy and recursively explores all connected infected cells.\n\n```\ndef quarantine(i, j):\n```\n\nThis function sets all cells in an infected region (starting from (i, j)) to a state \'2\', indicating that they have been quarantined.\n\nMain Loop:\nThe main logic resides in a loop that runs until all infected regions are quarantined.\n\nvisited keeps track of the cells that have been already processed.\nregions stores details about each infected region (set of cells it can infect, number of walls to quarantine it, and a representative cell).\nEach round:\n\nFind all infected regions and the cells they can infect.\nChoose the region that can infect the maximum number of cells and quarantine it.\nLet the other regions infect their neighboring cells.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def containVirus(self, mat: List[List[int]]) -> int:\n m, n = len(mat), len(mat[0])\n DIRECTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n \n def dfs(i, j, visited):\n if not (0 <= i < m and 0 <= j < n) or (i, j) in visited:\n return set(), 0\n if mat[i][j] == 2:\n return set(), 0\n elif mat[i][j] == 0:\n return {(i, j)}, 1\n \n visited.add((i, j))\n infected, walls = set(), 0\n for dx, dy in DIRECTIONS:\n ni, nj = i + dx, j + dy\n next_infected, next_walls = dfs(ni, nj, visited)\n infected |= next_infected\n walls += next_walls\n return infected, walls\n \n def quarantine(i, j):\n if 0 <= i < m and 0 <= j < n and mat[i][j] == 1:\n mat[i][j] = 2\n for dx, dy in DIRECTIONS:\n quarantine(i + dx, j + dy)\n \n ans = 0\n while True:\n visited, regions = set(), []\n for i in range(m):\n for j in range(n):\n if mat[i][j] == 1 and (i, j) not in visited:\n infected, walls = dfs(i, j, visited)\n if infected:\n regions.append((infected, walls, (i, j)))\n \n if not regions:\n break\n \n regions.sort(key=lambda x: (-len(x[0]), x[1]))\n max_infected, max_walls, start = regions[0]\n ans += max_walls\n quarantine(*start)\n \n for region in regions[1:]:\n for i, j in region[0]:\n mat[i][j] = 1\n \n return ans\n\n``` | 3 | 0 | ['Array', 'Depth-First Search', 'Breadth-First Search', 'Matrix', 'Simulation', 'Python', 'Python3'] | 0 |
contain-virus | Trying to understand a test case | trying-to-understand-a-test-case-by-magi-7ed7 | Can someone please explain why the expected output is 38 for the below input?\n\nInput:\n[[0,1,0,1,1,1,1,1,1,0],[0,0,0,1,0,0,0,0,0,0],[0,0,1,1,1,0,0,0,1,0],[0,0 | magicgnome | NORMAL | 2018-11-04T20:35:56.962907+00:00 | 2018-11-04T20:35:56.962946+00:00 | 471 | false | Can someone please explain why the expected output is 38 for the below input?\n\nInput:\n[[0,1,0,1,1,1,1,1,1,0],[0,0,0,1,0,0,0,0,0,0],[0,0,1,1,1,0,0,0,1,0],[0,0,0,1,1,0,0,1,1,0],[0,1,0,0,1,0,1,1,0,1],[0,0,0,1,0,1,0,1,1,1],[0,1,0,0,1,0,0,1,1,0],[0,1,0,1,0,0,0,1,1,0],[0,1,1,0,0,1,1,0,0,1],[1,0,1,1,0,1,0,1,0,1]]\n\nExpected: 38\nMy output: 40\n\n```\nH= Healthy Q = Quarentine\nI = Infected W = Wall\nInitial:\nH, ,I, ,H, ,I, ,I, ,I, ,I, ,I, ,I, ,H,\n , , , , , , , , , , , , , , , , , , ,\nH, ,H, ,H, ,I, ,H, ,H, ,H, ,H, ,H, ,H,\n , , , , , , , , , , , , , , , , , , ,\nH, ,H, ,I, ,I, ,I, ,H, ,H, ,H, ,I, ,H,\n , , , , , , , , , , , , , , , , , , ,\nH, ,H, ,H, ,I, ,I, ,H, ,H, ,I, ,I, ,H,\n , , , , , , , , , , , , , , , , , , ,\nH, ,I, ,H, ,H, ,I, ,H, ,I, ,I, ,H, ,I,\n , , , , , , , , , , , , , , , , , , ,\nH, ,H, ,H, ,I, ,H, ,I, ,H, ,I, ,I, ,I,\n , , , , , , , , , , , , , , , , , , ,\nH, ,I, ,H, ,H, ,I, ,H, ,H, ,I, ,I, ,H,\n , , , , , , , , , , , , , , , , , , ,\nH, ,I, ,H, ,I, ,H, ,H, ,H, ,I, ,I, ,H,\n , , , , , , , , , , , , , , , , , , ,\nH, ,I, ,I, ,H, ,H, ,I, ,I, ,H, ,H, ,I,\n , , , , , , , , , , , , , , , , , , ,\nI, ,H, ,I, ,I, ,H, ,I, ,H, ,I, ,H, ,I,\n\nAfter first quarentine: Total walls = 22\n\nH, ,I, ,H, ,I, ,I, ,I, ,I, ,I, ,I, ,H,\n , , , , , , , , , , , , , , , , , , ,\nH, ,H, ,H, ,I, ,H, ,H, ,H, ,H, ,H, ,H,\n , , , , , , , , , , , , , , , ,W, , ,\nH, ,H, ,I, ,I, ,I, ,H, ,H, ,H,W,Q,W,H,\n , , , , , , , , , , , , , ,W, , , , ,\nH, ,H, ,H, ,I, ,I, ,H, ,H,W,Q, ,Q,W,H,\n , , , , , , , , , , , ,W, , , ,W, ,W,\nH, ,I, ,H, ,H, ,I, ,H,W,Q, ,Q,W,H,W,Q,\n , , , , , , , , , , , ,W, , , ,W, , ,\nH, ,H, ,H, ,I, ,H, ,I, ,H,W,Q, ,Q, ,Q,\n , , , , , , , , , , , , , , , , , ,W,\nH, ,I, ,H, ,H, ,I, ,H, ,H,W,Q, ,Q,W,H,\n , , , , , , , , , , , , , , , , , , ,\nH, ,I, ,H, ,I, ,H, ,H, ,H,W,Q, ,Q,W,H,\n , , , , , , , , , , , , , ,W, ,W, , ,\nH, ,I, ,I, ,H, ,H, ,I, ,I, ,H, ,H, ,I,\n , , , , , , , , , , , , , , , , , , ,\nI, ,H, ,I, ,I, ,H, ,I, ,H, ,I, ,H, ,I,\n\nAfter first spread:\n\nI, ,I, ,I, ,I, ,I, ,I, ,I, ,I, ,I, ,I,\n , , , , , , , , , , , , , , , , , , ,\nH, ,I, ,I, ,I, ,I, ,I, ,I, ,I, ,I, ,H,\n , , , , , , , , , , , , , , , ,W, , ,\nH, ,I, ,I, ,I, ,I, ,I, ,H, ,H,W,Q,W,H,\n , , , , , , , , , , , , , ,W, , , , ,\nH, ,I, ,I, ,I, ,I, ,I, ,H,W,Q, ,Q,W,H,\n , , , , , , , , , , , ,W, , , ,W, ,W,\nI, ,I, ,I, ,I, ,I, ,I,W,Q, ,Q,W,H,W,Q,\n , , , , , , , , , , , ,W, , , ,W, , ,\nH, ,I, ,I, ,I, ,I, ,I, ,I,W,Q, ,Q, ,Q,\n , , , , , , , , , , , , , , , , , ,W,\nI, ,I, ,I, ,I, ,I, ,I, ,H,W,Q, ,Q,W,H,\n , , , , , , , , , , , , , , , , , , ,\nI, ,I, ,I, ,I, ,I, ,I, ,I,W,Q, ,Q,W,I,\n , , , , , , , , , , , , , ,W, ,W, , ,\nI, ,I, ,I, ,I, ,I, ,I, ,I, ,I, ,I, ,I,\n , , , , , , , , , , , , , , , , , , ,\nI, ,I, ,I, ,I, ,I, ,I, ,I, ,I, ,I, ,I,\n\nAfter second quarentine: Total walls = 40\nQ, ,Q, ,Q, ,Q, ,Q, ,Q, ,Q, ,Q, ,Q, ,Q,\nW, , , , , , , , , , , , , , , , , ,W,\nH,W,Q, ,Q, ,Q, ,Q, ,Q, ,Q, ,Q, ,Q,W,H,\n , , , , , , , , , , , ,W, ,W, ,W, , ,\nH,W,Q, ,Q, ,Q, ,Q, ,Q,W,H, ,H,W,Q,W,H,\n , , , , , , , , , , , , , ,W, , , , ,\nH,W,Q, ,Q, ,Q, ,Q, ,Q,W,H,W,Q, ,Q,W,H,\nW, , , , , , , , , , , ,W, , , ,W, ,W,\nQ, ,Q, ,Q, ,Q, ,Q, ,Q,W,Q, ,Q,W,H,W,Q,\nW, , , , , , , , , , , ,W, , , ,W, , ,\nH,W,Q, ,Q, ,Q, ,Q, ,Q, ,Q,W,Q, ,Q, ,Q,\nW, , , , , , , , , , , ,W, , , , , ,W,\nQ, ,Q, ,Q, ,Q, ,Q, ,Q,W,H,W,Q, ,Q,W,H,\n , , , , , , , , , , , ,W, , , , , ,W,\nQ, ,Q, ,Q, ,Q, ,Q, ,Q, ,Q,W,Q, ,Q,W,Q,\n , , , , , , , , , , , , , ,W, ,W, , ,\nQ, ,Q, ,Q, ,Q, ,Q, ,Q, ,Q, ,Q, ,Q, ,Q,\n , , , , , , , , , , , , , , , , , , ,\nQ, ,Q, ,Q, ,Q, ,Q, ,Q, ,Q, ,Q, ,Q, ,Q,\n``` | 3 | 0 | [] | 3 |
contain-virus | I can Guarantee you that The Cleanest Code You'll Ever See with Best in class Explanation !!! | i-can-guarantee-you-that-the-cleanest-co-w6zy | Intuition :-
Simulation
Max Heap
DFS
Approach :-
Helper Classes :-
Pair Class :
row - To store the row of a cell.
column- To store the column of cell.
Regi | Jagadish_Shankar | NORMAL | 2024-12-13T10:57:12.055809+00:00 | 2024-12-13T11:05:10.168989+00:00 | 250 | false | # Intuition :-\n\n- Simulation\n- Max Heap\n- DFS\n\n# Approach :-\n\n1) **Helper Classes :-**\n\n 1) ```Pair``` Class :\n - ```row``` - To store the row of a cell.\n - ```column```- To store the column of cell.\n \n 2) ```Region_Data``` Class :\n - ```walls_required_count``` - Number of walls required to contain the region.\n - ```uninfected_cells_count``` - Number of uninfected cells adjacent to the region.\n - ```infected_cells_list``` - List of cells which are infected in the region.\n\n2) **DFS Traversal** ```depth_first_search()``` :-\n\n - Parameters :-\n\n - ```current_i``` and ```current_j``` : The current position in the matrix.\n - ```R``` and ```C``` : Dimensions of the matrix.\n - ```matrix``` : The input matrix where ,\n - ```1``` indicates infected cells.\n - ```0``` indicates uninfected cells.\n - ```-999``` indicates already contained cells.\n - ```visited_matrix``` : Tracks whether a cell has already been visited during the current DFS traversal.\n - ```uninfected_cells_visited_matrix``` : Tracks uninfected cells adjacent to the infected region (to avoid counting the same cell multiple times).\n - ```region_data_object``` : Stores details about the current region (infected cells list , walls required count , uninfected cells count).\n \n - Explanation :-\n \n - Step - 1 is to Mark Current Cell as Visited\n \n ```\n visited_matrix[current_i][current_j] = true;\n\n region_data_object.infected_cells_list.add((new Pair(current_i, current_j)));\n ```\n\n - The current cell is marked as visited to avoid revisiting it in the DFS traversal.\n - Add the current infected cell\'s coordinates to the list of infected cells in this region.\n \n - Step - 2 is to Explore All Four Directions\n\n ```\n for (int[] coordinates_array : four_directions_array) {\n int next_i = current_i + coordinates_array[0];\n int next_j = current_j + coordinates_array[1];\n ```\n \n - Use ```four_directions_array``` (up , down , left , right) to compute the adjacent cells.\n \n - Step - 3 is Check Boundaries and Cell States\n\n ```\n if (is_within_bounds(next_i, next_j, R, C) && matrix[next_i][next_j] != -999 && !visited_matrix[next_i][next_j]) {\n ```\n\n - Ensure the next cell is:\n - Within the matrix boundaries ```(is_within_bounds(next_i , next_j , R , C))```\n - Not already contained ```(matrix[next_i][next_j] != -999)```\n - Not already visited ```(!visited_matrix[next_i][next_j])```\n\n - Step - 4 is to Handle Infected Cell ```(matrix[next_i][next_j] == 1)```\n ```\n if(matrix[next_i][next_j] == 1){\n depth_first_search(next_i , next_j , R , C , matrix , visited_matrix , uninfected_cells_visited_matrix , region_data_object);\n }\n ```\n\n - If the adjacent cell is also infected (1), recursively call DFS on that cell to continue exploring the current region.\n\n\n - Step - 5 is to Handle Uninfected Cell ```(matrix[next_i][next_j] == 0)```\n \n ```\n else if(matrix[next_i][next_j] == 0){\n \n region_data_object.walls_required_count++;\n \n if(!uninfected_cells_visited_matrix[next_i][next_j]){\n uninfected_cells_visited_matrix[next_i][next_j] = true;\n region_data_object.uninfected_cells_count++;\n }\n }\n ```\n\n - If the adjacent cell is uninfected (0):\n - Increment the count of walls required for containment, as this cell is a boundary.\n - Check if this uninfected cell was already considered for this region as ```if(!uninfected_cells_visited_matrix[next_i][next_j]){```\n - If the above given condition is true then ,\n - Mark the current cell as visited in the ```uninfected_cells_visited_matrix```.\n - Increment the ```uninfected_cells_count``` in the ```region_data_object```.\n\n2) **Simulation** ```containVirus()``` :-\n\n - A ```while()``` loop is used to run the simulation logic and it stops the simulation when the ```max_heap``` is empty.\n - The ```max_heap``` will store the ```Region_Data```\'s Object and sorts them in descending order based on the ```uninfected_cells_count``` in the object.\n - It will go throught the ```matrix``` and finds the Region of infected part with the help of ```depth_first_search()```.\n - After the DFS traversal the ```region_data_object``` will have the necessity details of the region.\n - If the ```uninfected_cells_count``` in the ```region_data_object``` is greater than ```0``` then the ```region_data_object``` is added to the ```max_heap```.\n - If the ```max_heap``` is empty then break the ```while()``` loop.\n - Now the first ```Region_Data``` object from the ```max_heap``` is polled out and stored as ```region_data_object_with_maximum_uninfected_cells```.\n - Add the ```walls_required_count``` from the ```region_data_object_with_maximum_uninfected_cells``` to the ```total_walls_required_count```.\n - Now mark the cells in the ```infected_cells_list``` in the ```region_data_object_with_maximum_uninfected_cells``` with value ```-999``` to indicate the cells are contained properly.\n - Now make a ```while()``` loop to run until the ```max_heap``` is empty and mark the adjacent cells (Four Directions) of the ```infected_cells_list``` of the ```Region_Data```\'s Object in the ```max_heap ``` which simulates the spread of the virus in the matrix.\n - Finally return the ```total_walls_required_count```.\n\n# Complexity\n\n- Time Complexity : $$O(T \xD7 (R \xD7 C + K logK))$$\n - R : Number of rows in the matrix.\n - C : Number of columns in the matrix.\n - K : Number of infected regions per iteration.\n - T : Number of iterations until the virus is fully contained.\n\n- Space Complexity : $$O(R x C)$$\n - For visited matrices , region data storage , and priority queue.\n\n# Code\n\n``` java []\n\nclass Pair {\n \n int row;\n \n int column;\n \n Pair(int row , int column){\n \n this.row = row;\n \n this.column = column;\n }\n}\n\nclass Region_Data {\n \n int walls_required_count;\n \n int uninfected_cells_count;\n \n List<Pair> infected_cells_list;\n \n Region_Data(){\n \n walls_required_count = 0;\n \n uninfected_cells_count = 0;\n \n infected_cells_list = new ArrayList<>();\n }\n}\n\nclass Solution {\n \n int[][] four_directions_array = new int[][] {{-1 , 0} , {1 , 0} , {0 , -1} , {0 , 1}};\n \n public boolean is_within_bounds(int current_i , int current_j , int R , int C){\n \n return ((current_i >= 0) && (current_i < R) && (current_j >= 0) && (current_j < C));\n }\n \n public void depth_first_search(int current_i , int current_j , int R , int C , int[][] matrix , boolean[][] visited_matrix , boolean[][] uninfected_cells_visited_matrix , Region_Data region_data_object){\n \n visited_matrix[current_i][current_j] = true;\n \n region_data_object.infected_cells_list.add((new Pair(current_i , current_j)));\n \n for(int[] coordinates_array : four_directions_array){\n \n int next_i = (current_i + coordinates_array[0]);\n \n int next_j = (current_j + coordinates_array[1]);\n \n if((is_within_bounds(next_i , next_j , R , C)) && (matrix[next_i][next_j] != -999) && (!visited_matrix[next_i][next_j])){\n \n if(matrix[next_i][next_j] == 1){\n depth_first_search(next_i , next_j , R , C , matrix , visited_matrix , uninfected_cells_visited_matrix , region_data_object);\n }else if(matrix[next_i][next_j] == 0){\n \n region_data_object.walls_required_count++;\n \n if(!uninfected_cells_visited_matrix[next_i][next_j]){\n uninfected_cells_visited_matrix[next_i][next_j] = true;\n region_data_object.uninfected_cells_count++;\n }\n }\n }\n }\n }\n \n public int containVirus(int[][] matrix){\n \n int total_walls_required_count = 0;\n \n int R = matrix.length;\n \n int C = matrix[0].length;\n \n while(true){\n \n PriorityQueue<Region_Data> max_heap = new PriorityQueue<>((a , b) -> (b.uninfected_cells_count - a.uninfected_cells_count));\n \n boolean[][] visited_matrix = new boolean[R][C];\n \n for(int i = 0 ; (i < R) ; i++){\n \n for(int j = 0 ; (j < C) ; j++){\n \n if((!visited_matrix[i][j]) && (matrix[i][j] == 1)){\n \n Region_Data region_data_object = new Region_Data();\n \n depth_first_search(i , j , R , C , matrix , visited_matrix , (new boolean[R][C]) , region_data_object);\n \n if(region_data_object.uninfected_cells_count > 0){\n max_heap.add(region_data_object);\n }\n }\n }\n }\n \n if(max_heap.isEmpty()){\n break;\n }\n \n Region_Data region_data_object_with_maximum_uninfected_cells = max_heap.poll();\n \n total_walls_required_count += region_data_object_with_maximum_uninfected_cells.walls_required_count;\n \n for(Pair pair_object : region_data_object_with_maximum_uninfected_cells.infected_cells_list){\n matrix[pair_object.row][pair_object.column] = -999;\n }\n \n while(!max_heap.isEmpty()){\n \n for(Pair pair_object : max_heap.poll().infected_cells_list){\n \n int current_i = pair_object.row;\n \n int current_j = pair_object.column;\n \n for(int[] coordinates_array : four_directions_array){\n \n int next_i = (current_i + coordinates_array[0]);\n \n int next_j = (current_j + coordinates_array[1]);\n \n if((is_within_bounds(next_i , next_j , R , C)) && (matrix[next_i][next_j] == 0)){\n matrix[next_i][next_j] = 1;\n }\n }\n }\n }\n }\n \n return total_walls_required_count;\n }\n}\n``` | 2 | 0 | ['Depth-First Search', 'Breadth-First Search', 'Heap (Priority Queue)', 'Matrix', 'Simulation', 'Java'] | 0 |
contain-virus | BEAT 100% || C++ | beat-100-c-by-antony_ft-mnkh | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | antony_ft | NORMAL | 2023-07-30T15:57:21.686185+00:00 | 2023-07-30T15:57:21.686202+00:00 | 116 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nint mp[2652], *zp[2652], zc[2652], step, mk;\n\nint dfs(int *p) {\n *p = 2;\n int res = 0;\n for (int *nb : {p-step, p-1, p+1, p+step}) {\n int v = *nb;\n if (v == mk || v > 1) continue;\n if (v <= 0) *nb = mk, ++res; else res += dfs(nb);\n }\n return res;\n}\nint dfs2(int *p) {\n *p = 1000;\n int res = 0;\n for (int *nb : {p-step, p-1, p+1, p+step}) {\n int v = *nb;\n if (v == 2) res += dfs2(nb); else if (v <= 0) ++res, *nb = 0;\n }\n return res;\n}\nvoid dfs3(int *p) {\n *p = 1;\n for (int *nb : {p-step, p-1, p+1, p+step}) {\n int v = *nb;\n if (v == 2) dfs3(nb); else if (v <= 0) *nb = 1;\n }\n}\nclass Solution {\npublic:\n int containVirus(vector<vector<int>>& isInfected) {\n step = isInfected[0].size() + 1; mk = 0;\n {\n int *p = mp+step;\n fill(mp, p, 1000);\n for (const auto &r : isInfected) {\n for (int x : r) *p++ = x;\n *p++ = 1000;\n }\n fill(p, p+step, 1000);\n }\n int *lo = mp+step, *hi = lo + step*isInfected.size(), res = 0;\n while(1) {\n int nb = 0;\n for (int *p = lo; p != hi; ++p) if (*p == 1) zp[nb] = p, --mk, zc[nb++] = dfs(p);\n if (nb == 0) break;\n\n int best = 0;\n for (int i = 1; i < nb; ++i) if (zc[i] > zc[best]) best = i;\n if (!zc[best]) break;\n res += dfs2(zp[best]);\n\n for (int *p = lo; p != hi; ++p) if (*p == 2) dfs3(p);\n }\n return res;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
contain-virus | BFS: A Step-by-Step Guide with Comments. | bfs-a-step-by-step-guide-with-comments-b-qvfu | Template for BFS\n\n1. bfs = deque() # to store the node first meets the requirements\n2. while bfs: # there are still nodes to visit\n3. node = bfs.popleft | ShutingLuo | NORMAL | 2023-03-05T15:29:44.597770+00:00 | 2023-03-05T15:29:44.597813+00:00 | 245 | false | # Template for BFS\n```\n1. bfs = deque() # to store the node first meets the requirements\n2. while bfs: # there are still nodes to visit\n3. node = bfs.popleft()\n4. # Mark as visited\n5. # Expand the node in all four directions\n6. if not visited and within the valid range:\n7. # update and do something\n```\n# Breaking Down the Solution"\n\n```\n# 1. BFS\n# Get to-spread/to-put-wall area. \n# Get nums of walls for every area. \n\n# Situation 1:\n# 2. none infected areas\n if not neighbors:\n break\n\n# Situation 2: \n# 3. Keep going\n# calculate the largest area:\n# 4. update the ans\n\n# 5. mark as processed and modify the unprocessed\n \n# 6. mark the spreaded\n \n```\n\n\n\n# Code\n```\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n m, n = len(isInfected), len(isInfected[0])\n ans = 0\n while True:\n # 1. BFS\n # neighbors stores every to-spread/to-put-wall area. \n # firewalls stores the countings for every area. \n neighbors, firewalls = list(), list()\n for i in range(m):\n for j in range(n):\n if isInfected[i][j] == 1:\n # detect the infected area \n q = deque([(i, j)])\n # index of this area\n idx = len(neighbors) + 1\n # record all cells in this to-spread/to-put-wall area\n neighbor = set()\n # count walls needed\n firewall = 0\n # mark as visited\n isInfected[i][j] = -idx\n\n while q:\n x, y = q.popleft()\n for d in range(4):\n # detect around\n nx, ny = x + dirs[d][0], y + dirs[d][1]\n # ensure within the matrix\n if 0 <= nx < m and 0 <= ny < n:\n if isInfected[nx][ny] == 1:\n # update infected area\n q.append((nx, ny))\n # mark as visited\n isInfected[nx][ny] = -idx\n elif isInfected[nx][ny] == 0:\n # update counting and neighbor\n firewall += 1\n neighbor.add((nx, ny))\n\n \n \n # update neighbors and firewalls\n neighbors.append(neighbor)\n firewalls.append(firewall)\n\n # 2. none infected areas\n if not neighbors:\n break\n \n # 3. calculate the largest area:\n idx = 0\n for i in range(1, len(neighbors)):\n if len(neighbors[i]) > len(neighbors[idx]):\n idx = i\n \n # 4. update the ans\n ans += firewalls[idx]\n\n # if only 1 area in total, this is the final answer\n if len(neighbors) == 1:\n # return ans\n break \n \n\n # 5. mark as processed and modify the unprocessed\n for i in range(m):\n for j in range(n):\n if isInfected[i][j] < 0:\n # unprocess\n if isInfected[i][j] != - (idx + 1):\n isInfected[i][j] = 1\n else:\n isInfected[i][j] = 2\n # 6. mark the spreaded\n for i, neighbor in enumerate(neighbors):\n if i != idx:\n # spread\n for x, y in neighbor:\n isInfected[x][y] = 1\n \n \n\n return ans\n``` | 2 | 0 | ['Breadth-First Search', 'Python3'] | 0 |
contain-virus | c++ | easy | short | c-easy-short-by-venomhighs7-rwyi | \n# Code\n\nclass Solution {\npublic:\n vector<vector<int> > g;\n int n, m, c, mx, w, r, ans, itr;\n unordered_set<int> s;\n \n int dfs(int i, in | venomhighs7 | NORMAL | 2022-11-01T03:48:19.595344+00:00 | 2022-11-01T03:48:19.595388+00:00 | 1,363 | false | \n# Code\n```\nclass Solution {\npublic:\n vector<vector<int> > g;\n int n, m, c, mx, w, r, ans, itr;\n unordered_set<int> s;\n \n int dfs(int i, int j){\n if(i<0 || i>=n || j<0 || j>=m || g[i][j]!=1)\n return 0;\n int ans=0;\n if(i+1<n && g[i+1][j]==0){\n s.insert((i+1)*m+j);\n ans++;\n }\n if(i-1>=0 && g[i-1][j]==0){\n s.insert((i-1)*m+j);\n ans++;\n }\n if(j+1<m && g[i][j+1]==0){\n s.insert(i*m+(j+1));\n ans++;\n }\n if(j-1>=0 && g[i][j-1]==0){\n s.insert(i*m+(j-1));\n ans++;\n }\n g[i][j]=c;\n ans+=dfs(i+1, j);\n ans+=dfs(i-1, j);\n ans+=dfs(i, j+1);\n ans+=dfs(i, j-1);\n return ans; // total number of walls needed to block this connected component\n }\n \n int containVirus(vector<vector<int>>& grid) {\n g=grid, n=g.size(), m=g[0].size(), ans=0;\n while(true){\n c=2, mx=0;\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(g[i][j]==1){\n s.clear();\n int walls=dfs(i, j);\n if(mx<s.size()){\n mx=s.size();\n w=walls;\n r=c;\n }\n c++;\n }\n }\n }\n if(mx==0)\n break;\n ans+=w;\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(g[i][j]==r)\n g[i][j]=1e9;\n else if(g[i][j]>1 && g[i][j]!=1e9){\n g[i][j]=1;\n if(i+1<n && !g[i+1][j]) g[i+1][j]=1;\n if(i-1>=0 && !g[i-1][j]) g[i-1][j]=1;\n if(j+1<m && !g[i][j+1]) g[i][j+1]=1;\n if(j-1>=0 && !g[i][j-1]) g[i][j-1]=1;\n }\n }\n }\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
contain-virus | [Python3] brute-force | python3-brute-force-by-ye15-4css | \n\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n m, n = len(isInfected), len(isInfected[0])\n ans = 0 \n | ye15 | NORMAL | 2022-09-06T02:59:01.697884+00:00 | 2022-09-06T03:08:06.464095+00:00 | 656 | false | \n```\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n m, n = len(isInfected), len(isInfected[0])\n ans = 0 \n while True: \n regions = []\n fronts = []\n walls = []\n seen = set()\n for i in range(m): \n for j in range(n): \n if isInfected[i][j] == 1 and (i, j) not in seen: \n seen.add((i, j))\n stack = [(i, j)]\n regions.append([(i, j)])\n fronts.append(set())\n walls.append(0)\n while stack: \n r, c = stack.pop()\n for rr, cc in (r-1, c), (r, c-1), (r, c+1), (r+1, c): \n if 0 <= rr < m and 0 <= cc < n: \n if isInfected[rr][cc] == 1 and (rr, cc) not in seen: \n seen.add((rr, cc))\n stack.append((rr, cc))\n regions[-1].append((rr, cc))\n elif isInfected[rr][cc] == 0: \n fronts[-1].add((rr, cc))\n walls[-1] += 1\n if not regions: break\n idx = fronts.index(max(fronts, key = len))\n ans += walls[idx]\n for i, region in enumerate(regions): \n if i == idx: \n for r, c in region: isInfected[r][c] = -1 # mark as quaranteened \n else: \n for r, c in fronts[i]: isInfected[r][c] = 1 # mark as infected \n return ans \n``` | 2 | 0 | ['Python3'] | 0 |
contain-virus | Python BFS simulation solution: nothing convoluted | python-bfs-simulation-solution-nothing-c-nlbp | I guess one should attempt Leetcode 695. Max Area of Island before doing this problem. Just speeds up everything tremendously, no complicated algorithms or conc | huikinglam02 | NORMAL | 2022-06-30T18:24:27.926714+00:00 | 2022-06-30T18:24:27.926757+00:00 | 481 | false | I guess one should attempt Leetcode 695. Max Area of Island before doing this problem. Just speeds up everything tremendously, no complicated algorithms or concepts at all\nAlso, I highly recommend padding the boundary with 2, as a rigid wall is equivalent to a quarantined region\n```\nclass Solution:\n # Use 2 to pad the boundary\n # Cycle start\n # Use BFS to identify connected components\n # In the process also calculate the perimeter\n # Important point to note: we choose group with largest number of 0 cells neighboring the 1s, not the perimeter\n # Choose region with the affected neighbours to install wall (perimeter), mark the region to be 2\n # Then for all infected regions, expand the boundary for 1\n # Repeat the cycle until all regions become 2 (len(points) <= 1)\n \n def containVirus(self, isInfected: List[List[int]]) -> int:\n # Boundary padding\n self.grid = [[2]*(len(isInfected[0])+2)]\n for row in isInfected:\n self.grid.append([2] + row + [2])\n self.grid.append([2]*(len(isInfected[0])+2))\n \n # reused Leetcode 695. Max Area of Island code\n # BFS from each point with 1 \n m, n = len(self.grid), len(self.grid[0])\n neig = [[1,0],[-1,0],[0,1],[0,-1]]\n wall = 0\n finished = False\n \n while not finished:\n island_perimeters = []\n affected_cells = []\n points = []\n visited = set()\n for i in range(1,m-1):\n for j in range(1,n-1):\n if self.grid[i][j] == 1 and (i,j) not in visited:\n # BFS\n points.append(set())\n affected_cells.append(set())\n dq = deque()\n dq.append((i,j))\n visited.add((i,j))\n perimeter = 0\n while dq:\n x = dq.popleft()\n for k in range(4):\n xn, yn = x[0]+neig[k][0], x[1]+neig[k][1]\n if (xn,yn) not in visited and self.grid[xn][yn]==1:\n dq.append((xn,yn))\n visited.add((xn,yn))\n elif self.grid[xn][yn] == 0:\n perimeter += 1\n affected_cells[-1].add((xn,yn))\n points[-1].add(x)\n island_perimeters.append(perimeter)\n if not points:\n return wall\n max_affected, max_group = 0, 0\n for i, cells in enumerate(affected_cells):\n if len(cells) > max_affected:\n max_group = i\n max_affected = len(cells)\n wall += island_perimeters[max_group]\n \n # quarantined regions\n for point in points[max_group]:\n self.grid[point[0]][point[1]] = 2\n # evolve the infection\n if len(points) == 1:\n finished = True\n else:\n for j, point_set in enumerate(points):\n if j != max_group:\n for point in point_set:\n for k in range(4):\n xn, yn = point[0]+neig[k][0], point[1]+neig[k][1]\n if self.grid[xn][yn] == 0:\n self.grid[xn][yn] = 1\n return wall\n``` | 2 | 0 | [] | 0 |
contain-virus | Easy to understand | DFS | easy-to-understand-dfs-by-bnybny-fs7t | \nclass Group{\n public:\n \n set<pair<int,int>>ne;\n set<pair<int,int>>affected;\n \n int w;\n \n Group(){\n w = 0;\n }\n};\n | bnybny | NORMAL | 2022-06-22T20:11:07.585938+00:00 | 2022-06-22T20:16:13.725933+00:00 | 812 | false | ```\nclass Group{\n public:\n \n set<pair<int,int>>ne;\n set<pair<int,int>>affected;\n \n int w;\n \n Group(){\n w = 0;\n }\n};\n\n\n\nclass Solution {\npublic:\n \n bool isValid(int i,int j,int n,int m){\n return i>=0 && j>=0 && i<n && j<m;\n }\n \n int dir[4][2]={\n {1,0},\n {0,1},\n {-1,0},\n {0,-1}\n };\n \n\n void dfs(vector<vector<int>>&in,int i,int j,int n,int m,vector<vector<bool>>&vis,Group *g){\n \n if(in[i][j]==-1) return;\n \n if(in[i][j] ==0 ){\n g->w++;\n g->ne.insert({i,j});\n return;\n }\n \n vis[i][j] = 1;\n \n if(in[i][j] == 1)\n g->affected.insert({i,j});\n \n \n for(int k=0;k<4;k++){\n \n int x = i+dir[k][0], y = j+dir[k][1];\n \n if(isValid(x,y,n,m) && !vis[x][y]) \n dfs(in,i+dir[k][0],j+dir[k][1],n,m,vis,g);\n }\n \n }\n \n \n int containVirus(vector<vector<int>>& in) {\n \n int n = in.size(),m = in[0].size(),ans = 0;\n \n \n while(1){\n \n vector<Group *>v;\n \n vector<vector<bool>>visited(n,vector<bool>(m,0));\n \n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(!visited[i][j] && in[i][j]==1){\n \n Group *g = new Group();\n dfs(in,i,j,n,m,visited,g);\n \n v.push_back(g);\n }\n \n }\n }\n \n \n if(v.size()==0) break;\n \n \n int mx = 0,index = 0;\n \n for(int i=0;i<v.size();i++){\n if(v[i]->ne.size()>mx){\n mx = v[i]->ne.size();\n index = i;\n }\n }\n \n Group * x = v[index];\n \n ans+=(x->w);\n \n \n for(auto itr:x->affected){\n in[itr.first][itr.second] = -1;\n }\n \n \n for(int i=0;i<v.size();i++){\n if(i==index) continue;\n x = v[i];\n for(auto itr:x->ne){\n in[itr.first][itr.second] = 1;\n }\n \n }\n \n \n }\n \n return ans;\n }\n};\n``` | 2 | 0 | ['Depth-First Search', 'C'] | 0 |
contain-virus | Java clean | java-clean-by-rexue70-2fvi | Very short Java\n\n1. we calculate score of island(means how many island it can infect next), border of island\n2. pick the max score island and delete it, add | rexue70 | NORMAL | 2020-05-08T05:46:15.315156+00:00 | 2020-05-08T05:47:55.425388+00:00 | 671 | false | Very short Java\n\n1. we calculate score of island(means how many island it can infect next), border of island\n2. pick the max score island and delete it, add border of that island to result\n3. extend infection to next day, all remaining island expand.\n\n```\nclass Solution {\n int m, n, id;\n int[][] dirs = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};\n public int containVirus(int[][] grid) {\n m = grid.length; n = grid[0].length; \n int res = 0;\n while (true) {\n id = 0;\n Set<Integer> visited = new HashSet<>();\n Map<Integer, Set<Integer>> islands = new HashMap<>(), scores = new HashMap<>();\n Map<Integer, Integer> walls = new HashMap<>();\n for (int i = 0; i < m; i++) \n for (int j = 0; j < n; j++)\n if (grid[i][j] == 1 && !visited.contains(i * n + j))\n dfs(i, j, visited, grid, islands, scores, walls, id++);\n if (islands.isEmpty()) break;\n int maxVirus = 0;\n for (int i = 0; i < id; i++)\n if (scores.getOrDefault(maxVirus, new HashSet<>()).size() < scores.getOrDefault(i, new HashSet<>()).size())\n maxVirus = i;\n res += walls.getOrDefault(maxVirus, 0);\n for (int i = 0; i < islands.size(); i++)\n for (int island : islands.get(i)) {\n int x = island / n, y = island % n;\n if (i == maxVirus) grid[x][y] = -1; \n else { \n for (int [] dir : dirs) {\n int nx = x + dir[0], ny = y + dir[1];\n if (nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] == 0) \n grid[nx][ny] = 1;\n }\n } \n }\n }\n return res;\n }\n \n private void dfs(int i, int j, Set<Integer> visited, int[][] grid, Map<Integer, Set<Integer>> islands, Map<Integer, Set<Integer>> scores, Map<Integer, Integer> walls, int id) {\n if (!visited.add(i * n + j)) return;\n islands.computeIfAbsent(id, value -> new HashSet<>()).add(i * n + j);\n for (int[] dir : dirs) {\n int x = i + dir[0], y = j + dir[1];\n if (x < 0 || x >= m || y < 0 || y >= n) continue;\n if (grid[x][y] == 1) dfs(x, y, visited, grid, islands, scores, walls, id);\n if (grid[x][y] == 0) {\n scores.computeIfAbsent(id, value -> new HashSet<>()).add(x * n + y);\n walls.put(id, walls.getOrDefault(id, 0) + 1);\n }\n }\n }\n}\n``` | 2 | 0 | [] | 0 |
contain-virus | longest solution I've ever written on leetcode. 1A, love u all | longest-solution-ive-ever-written-on-lee-8hcs | \nclass Pos {\n int x;\n int y;\n\n Pos(int x, int y) {\n this.x = x;\n this.y = y;\n }\n}\n\nclass Solution {\n private static fin | solaaoi | NORMAL | 2018-04-21T03:35:11.522155+00:00 | 2018-04-21T03:35:11.522155+00:00 | 600 | false | ```\nclass Pos {\n int x;\n int y;\n\n Pos(int x, int y) {\n this.x = x;\n this.y = y;\n }\n}\n\nclass Solution {\n private static final int MAX_N = 50;\n private static final int dr[] = {-1, 1, 0, 0};\n private static final int dc[] = {0, 0, -1, 1};\n\n private static boolean[][] vis = new boolean[MAX_N][MAX_N];\n\n private int numVirus(int[][] grid, int x, int y) {\n int row = grid.length;\n int col = grid[0].length;\n\n int res = 0;\n vis[x][y] = true;\n for (int i = 0; i < 4; ++i) {\n int nx = x + dr[i];\n int ny = y + dc[i];\n if (nx >= 0 && nx < row && ny >= 0 && ny < col ) {\n if (grid[nx][ny] == 0) {\n ++res;\n grid[nx][ny] = 3;\n } else if (grid[nx][ny] == 1 && !vis[nx][ny]) {\n res += numVirus(grid, nx, ny);\n }\n }\n }\n return res;\n }\n\n private Pos maxRegion(int[][] grid) {\n int x = -1;\n int y = -1;\n int cnt = 0;\n\n for (int i = 0; i < MAX_N; ++i) {\n for (int j = 0; j < MAX_N; ++j) {\n vis[i][j] = false;\n }\n }\n\n int row = grid.length;\n int col = grid[0].length;\n for (int i = 0; i < row; ++i) {\n for (int j = 0; j < col; ++j) {\n if (grid[i][j] == 1 && !vis[i][j]) {\n int num = numVirus(grid, i, j);\n if (num > cnt) {\n x = i;\n y = j;\n cnt = num;\n }\n for (int a = 0; a < row; ++a) {\n for (int b = 0; b < col; ++b) {\n if (grid[a][b] == 3) {\n grid[a][b] = 0;\n }\n }\n }\n }\n }\n }\n\n return new Pos(x, y);\n }\n\n private int buildWalls(int[][] grid, int x, int y) {\n int row = grid.length;\n int col = grid[0].length;\n\n grid[x][y] = 2;\n int res = 0;\n for (int i = 0; i < 4; ++i) {\n int nx = x + dr[i];\n int ny = y + dc[i];\n if (nx >= 0 && nx < row && ny >= 0 && ny < col) {\n if (grid[nx][ny] == 0) {\n ++res;\n } else if (grid[nx][ny] == 1) {\n res += buildWalls(grid, nx, ny);\n }\n }\n }\n\n return res;\n }\n\n private void expand(int[][] grid) {\n int row = grid.length;\n int col = grid[0].length;\n for (int i = 0; i < row; ++i) {\n for (int j = 0; j < col; ++j) {\n if (grid[i][j] == 1) {\n for (int d = 0; d < 4; ++d) {\n int ni = i + dr[d];\n int nj = j + dc[d];\n if (ni >= 0 && ni < row && nj >= 0 && nj < col && grid[ni][nj] == 0) {\n grid[ni][nj] = 3;\n }\n }\n }\n }\n }\n\n for (int i = 0; i < row; ++i) {\n for (int j = 0; j < col; ++j) {\n if (grid[i][j] == 3) {\n grid[i][j] = 1;\n }\n } \n }\n }\n\n public int containVirus(int[][] grid) {\n int res = 0;\n Pos pos = maxRegion(grid);\n\n while (pos.x != -1 && pos.y != -1) {\n res += buildWalls(grid, pos.x, pos.y);\n expand(grid);\n pos = maxRegion(grid);\n }\n\n return res;\n }\n}\n\n\n``` | 2 | 0 | [] | 0 |
contain-virus | Concise solution, no index tracking (detailed explanation with illustration) | concise-solution-no-index-tracking-detai-5sz2 | The idea is to find all infected regions and identify the most dangerous one (i.e., infecting most uninfected cells), then update all regions by the rule and re | zzg_zzm | NORMAL | 2017-12-19T05:59:23.594000+00:00 | 2017-12-19T05:59:23.594000+00:00 | 649 | false | The idea is to find all infected regions and identify the most dangerous one (i.e., infecting most uninfected cells), then update all regions by the rule and repeat this process until no more infected regions found.\n\nTo accomplish this algorithm, it is useful to define structure `Region` as\n```cpp\n struct Region {\n unordered_set<int*> inner, border;\n size_t perimeter = 0;\n };\n```\nwhere \n* `inner`: reference to values of inner infected cells \n* `border`: reference to values of *uninfected* cells surrounding inner cells\n* `perimeter`: count of edges between `inner` and `border`\n \n**NOTE:** Define `inner` and `border` as value references instead of tracking `(i,j)` indices to save space and avoid copies.\n\n**Algorithm Outline:**\n1. For each day, scan entire grid to find all infected regions `regions` and the max count of `border`. This could be accomplished by either DFS or BFS.\n1. if `regions` is empty, quit; \notherwise,\n * for the most dangerous region `r`, set `r.inner` to value `-1` (i.e., quarantined);\n * for other regions `r`, set `r.border` to value `1` (i.e., infected), and accumulate `r.perimeter` (i.e., build new walls) \n\n```cpp \n int containVirus(vector<vector<int>>& grid) \n { \n for (size_t walls = 0, maxborder = 0; true; )\n { \n // find all infected regions\n auto regions = findRegions(grid, maxborder); \n if (regions.empty()) return walls; // no more infection\n \n // update all regions\n for (auto& r : regions)\n if (r.border.size() != maxborder) { // infected\n for (auto& cell : r.inner) *cell = 1;\n for (auto& cell : r.border) *cell = 1;\n }\n else walls += r.perimeter; // quarantined\n } \n } \n```\nDFS routine to explore a region starting at cell `(i,j)`:\n```cpp \n void dfs(vector<vector<int>>& grid, int i, int j, Region& r) \n {\n // no need to explore if already quarantined\n if (min(i,j)<0 || i>=grid.size() || j>=grid[0].size() || grid[i][j]<0) return;\n \n if (grid[i][j]) { // infected\n r.inner.insert(&(grid[i][j]=-1));\n dfs(grid,i+1,j,r), dfs(grid,i,j+1,r), dfs(grid,i-1,j,r), dfs(grid,i,j-1,r);\n } // border found\n else r.border.insert(&grid[i][j]), ++r.perimeter; \n }; \n```\nFind all infected regions and get max border:\n```cpp \n vector<Region> findRegions(vector<vector<int>>& grid, size_t& maxborder) \n {\n vector<Region> regions; maxborder = 0;\n for (int i = 0; i < grid.size(); ++i)\n for (int j = 0; j < grid[0].size(); ++j)\n if (grid[i][j] == 1) {\n Region r; dfs(grid, i, j, r);\n regions.push_back(r); \n maxborder = max(maxborder, r.border.size());\n } \n return regions;\n }\n``` | 2 | 0 | ['Depth-First Search', 'C++'] | 1 |
contain-virus | clean python solution | clean-python-solution-by-erjoalgo-8eto | \nclass Solution(object):\n def containVirus(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n if not | erjoalgo | NORMAL | 2017-12-17T23:20:58.157000+00:00 | 2017-12-17T23:20:58.157000+00:00 | 969 | false | ```\nclass Solution(object):\n def containVirus(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n if not grid: return None\n N,M=len(grid),len(grid[0])\n \n def around(r,c,t=None):\n # all cells 1-step away from (r,c)\n # optionally, if t!=None, target value must be t\n for d in (-1,1):\n for (rr,cc) in ((r+d,c), (r,c+d)):\n if 0<=rr<N and 0<=cc<M and (t == None or grid[rr][cc]==t):\n yield (rr,cc)\n \n def regions():\n regs=[]\n seen=set()\n for r in xrange(N):\n for c in xrange(M):\n if grid[r][c]==1 and (r,c) not in seen:\n # this is a new region. do a BFS to find all contiguous ones\n reg=set()\n front, newfront=[(r,c)], []\n while front:\n reg.update(front)\n while front:\n (r,c) = front.pop()\n for (rr,cc) in around(r,c,1):\n if (rr, cc) not in reg:\n newfront.append((rr,cc))\n reg.add((rr, cc))\n front,newfront=newfront,front\n regs.append(reg)\n seen.update(reg)\n return regs\n \n def reg_boundary(reg):\n # cells that would become infected by cells in reg\n bound=set()\n for (r,c) in reg:\n for (rr,cc) in around(r,c,0):\n bound.add((rr,cc))\n\n return bound\n \n def reg_walls(reg,bound):\n # number of walls that would need to be built to contain reg\n walls=0\n for (r,c) in bound:\n for (rr,cc) in around(r,c,1):\n if (rr,cc) in reg:\n walls+=1 \n return walls\n gwalls=0\n \n while True:\n \n regs=regions()\n \n if not regs: break\n reg = max(regs, key=lambda reg: len(reg_boundary(reg)))\n walls=reg_walls(reg, reg_boundary(reg))\n gwalls+=walls\n \n # neutralize region\n for (r,c) in reg:\n grid[r][c]=2\n\n # compute next grid iteration after new infections\n infected=set()\n for r in xrange(N):\n for c in xrange(M):\n if grid[r][c]==1:\n for (rr, cc) in around(r, c, 0):\n infected.add((rr, cc))\n\n for r, c in infected:\n grid[r][c]=1\n\n if not infected: break\n\n return gwalls\n``` | 2 | 0 | [] | 2 |
contain-virus | Contain Virus Question | contain-virus-question-by-amphitter-kr35 | \n# Intuition\n- Identify Infected Regions: Use BFS or DFS to find all contiguous regions of infected cells (cells with value 1).\n\n- Calculate Threats and Wal | Amphitter | NORMAL | 2024-05-24T05:51:51.622364+00:00 | 2024-05-24T05:51:51.622394+00:00 | 106 | false | \n# Intuition\n- Identify Infected Regions: Use BFS or DFS to find all contiguous regions of infected cells (cells with value 1).\n\n- Calculate Threats and Walls: For each infected region, determine the number of uninfected cells it can potentially infect in the next step and calculate the number of walls needed to quarantine the region.\n\n- Select the Most Threatening Region: Choose the region that can potentially infect the most uninfected cells. This region should be quarantined by installing walls around it.\n\n- Quarantine and Spread: Quarantine the selected region by marking it so that it can no longer spread. Then, spread the virus from the remaining regions to their neighboring uninfected cells.\n\n- Repeat: Continue the above steps until no further spread is possible or all regions are quarantined.\n\n# Approach\n\nThe approach to solving the problem involves simulating the containment of the virus by installing walls to quarantine infected regions. Here\'s a detailed breakdown of the approach:\n\n**Identify Infected Regions:**\nUse Depth-First Search (DFS) or Breadth-First Search (BFS) to identify all contiguous regions of infected cells. This step helps partition the grid into separate infected regions.\n\n**Calculate Threats and Walls:**\nFor each infected region, determine the number of uninfected cells it can potentially infect in the next step. This represents the threat posed by the region.\nCalculate the number of walls needed to quarantine each region. Walls are installed on the shared boundary between infected and uninfected cells.\n\n**Select the Most Threatening Region:**\nIdentify the infected region that poses the highest threat, i.e., the region that can infect the most uninfected cells.\nPrioritize quarantining this region by installing walls around it.\n\n**Quarantine and Spread:**\nQuarantine the selected region by installing walls around it. This prevents the virus from spreading further from this region.\nLet the virus spread from other infected regions to neighboring uninfected cells. Update the infected cells accordingly.\n\n**Repeat Until Convergence:**\nRepeat the above steps until either all infected regions are quarantined or no further spread of the virus is possible.\nEach iteration involves selecting the most threatening region, quarantining it, and updating the infected cells.\n\n**Return the Total Number of Walls Used:**\nAfter containment is complete, return the total number of walls installed to quarantine all infected regions.\n\n# Complexity\n- Time complexity:\n$$O(m * n)$$\n\n- Space complexity:\n$$O(m * n)$$ \n\n# Code\n```\nclass Solution(object):\n def containVirus(self, isInfected):\n """\n :type isInfected: List[List[int]]\n :rtype: int\n """\n from collections import deque, defaultdict\n \n m, n = len(isInfected), len(isInfected[0])\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n \n def get_regions():\n visited = [[False] * n for _ in range(m)]\n regions = []\n for i in range(m):\n for j in range(n):\n if isInfected[i][j] == 1 and not visited[i][j]:\n queue = deque([(i, j)])\n region = []\n visited[i][j] = True\n while queue:\n x, y = queue.popleft()\n region.append((x, y))\n for dx, dy in directions:\n nx, ny = x + dx, y + dy\n if 0 <= nx < m and 0 <= ny < n and isInfected[nx][ny] == 1 and not visited[nx][ny]:\n visited[nx][ny] = True\n queue.append((nx, ny))\n regions.append(region)\n return regions\n \n def calculate_threats(region):\n threat_cells = set()\n walls_needed = 0\n for x, y in region:\n for dx, dy in directions:\n nx, ny = x + dx, y + dy\n if 0 <= nx < m and 0 <= ny < n and isInfected[nx][ny] == 0:\n threat_cells.add((nx, ny))\n walls_needed += 1\n return threat_cells, walls_needed\n \n total_walls = 0\n while True:\n regions = get_regions()\n if not regions:\n break\n \n max_threat_index = -1\n max_threat_count = -1\n threats = []\n walls_needed = []\n \n for i, region in enumerate(regions):\n threat_cells, walls = calculate_threats(region)\n threats.append(threat_cells)\n walls_needed.append(walls)\n if len(threat_cells) > max_threat_count:\n max_threat_count = len(threat_cells)\n max_threat_index = i\n \n if max_threat_index == -1:\n break\n \n total_walls += walls_needed[max_threat_index]\n \n for i, region in enumerate(regions):\n if i == max_threat_index:\n for x, y in region:\n isInfected[x][y] = -1 # Quarantine the region\n else:\n for x, y in threats[i]:\n isInfected[x][y] = 1 # Spread the virus\n \n return total_walls\n\n# Example usage\nsol = Solution()\nisInfected = [\n [0,1,0,0,0,0,0,1],\n [0,1,0,0,0,0,0,1],\n [0,0,0,0,0,0,0,1],\n [0,0,0,0,0,0,0,0]\n]\nprint(sol.containVirus(isInfected)) # Output: 10\n\n``` | 1 | 0 | ['Python'] | 0 |
contain-virus | Another Explanation, Python3, O(R*C*max(R,C)) time and O(R*C) space, Faster than 95% | another-explanation-python3-orcmaxrc-tim-q7ze | Intuition\n Describe your first thoughts on how to solve this problem. \n\nThis is a pretty hard problem, there\'s a lot going on. There are a lot of considerat | biggestchungus | NORMAL | 2023-07-25T02:08:33.453512+00:00 | 2023-07-25T02:08:33.453535+00:00 | 92 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThis is a pretty hard problem, there\'s a lot going on. There are a lot of considerations to make. But the idea is that the problem asks us to wall of clusters according to what happens each day/night, and explains the rules. So we simulate.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nI didn\'t come up with the solution, but thought that the existing solutions are kind of hard to read and understand what they\'re doing. So I made a `Cluster` structure and `findCluster` method to help break things up. The main loop is a lot easier to read after that.\n\nAs the problem says, for each day/night cycle:\n1. during the day, we find the cluster that threatens the most cells, then wall it off\n2. at night, the remaining cluster(s) expand by 1 in each cardinal direction\n\nSo to break it down, we need the following\n1. we need to identify all of the clusters\n2. for each cluster we need to know the cells in that cluster so we can wall it off, the adjacent healthy cells so we know how many there are, and the number of walls required to wall it off\n\nWhen we wall off a cluster, we set all of its cells to some marker value `-1`. Originally I struggled with marking off only the boundary to be more efficient. But that was making the solution too complicated so I simplified and just marked them all off.\n\nFollowing another solution, I made a little `Cluster` class that contains the details.\n\n**NOTE:** I struggled a lot initially because I tried to be fancy about unioning `Cluster`s together to avoid re-finding clusters at each step. Eventually I gave up because it was getting to complicated.\n\nTo make it work I\'d use something along the lines of union-find:\n* have an array that maps (r,c) to the index of the cluster containing it\n* have the usual findRoot and union methods of union-find to quickly unify clusters each night when they expand\n * having a set of coordinates for adjacent cells is easy to union: just merge the cells\n * to merge the number of walls, that\'s more complicated and where I started getting really confused. There\'s probably a simple expression after working through all the edge cases though\n\nIn the end, if all the complications are worked out and you only track boundary cells, the complexity of the solution problably drops to $O((R+C)*\\max(R,C))$.\n\n# Complexity\n- Time complexity: $$O(R*C*\\max(R,C)))$$\n\nI think that\'s right but I\'m not sure. The worst-case scenario is we have a bunch of isolated little clusters so we need a lot of iterations. The most iterations we will do is order $\\max(R,C)$ since clusters can\'t grow for more than that number of steps. In each iteration we do $O(R*C)$ work to find all the clusters.\n\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(R*C)$$\n\nAt worst we store every infected cell in 1 `Cluster`, and every healthy cel in 4 `Cluster`s. We also have the `visited` array with $R*C$ entries. So overall it\'s order $R*C$.\n\n# Code\n```\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n # ruh-roh...\n\n # each night we want to find\n # (1) all of the clusters\n # cells in the cluster\n # adjacent healthy cells\n # number of adjoining walls\n # (2) order clusters by num adjacent healthy cells\n # (3) pick cluster with most healthy cells\n\n R = len(isInfected)\n C = len(isInfected[0])\n\n class Cluster:\n def __init__(self):\n self.cells = set() # (r,c) of all infected cells in here\n self.risked = set() # (r,c) of all adjacent healthy cells\n self.walls = 0 # number of walls required to fence of this cluster\n\n def numRisked(self):\n return len(self.risked)\n\n def __repr__(self):\n return "Cluster(%i cells, %i risked, %i walls)" % (len(self.cells), len(self.risked), self.walls)\n\n fenced = -1\n\n def getCluster(i: int, j: int, visited: list[list[bool]]) -> \'Cluster\':\n cluster = Cluster()\n stack = [(i,j)]\n visited[i][j] = True\n while stack:\n (r,c) = stack.pop()\n cluster.cells.add((r,c))\n\n for dr,dc in [(-1,0), (+1,0), (0,-1), (0,+1)]:\n rr = r + dr\n cc = c + dc\n if rr >= 0 and rr < R and cc >= 0 and cc < C:\n if visited[rr][cc]:\n continue\n \n # not visited: is healthy or fenced off or infected\n if isInfected[rr][cc] == 1:\n # infected: add to stack and visited\n stack.append((rr,cc))\n visited[rr][cc] = True\n elif isInfected[rr][cc] == 0:\n # healthy\n cluster.walls += 1 # there\'s a border between (r,c) and (rr,cc)\n # print(" added wall between", (r,c), (rr,cc))\n cluster.risked.add((rr,cc))\n\n return cluster\n\n # when are we done? when there are no clusters\n # if there\'s one big cluster at the end (all infected), then number of fences will be zero because evrything is either\n # a fence for a boundary already\n\n walls = 0\n\n while True:\n clusters = []\n visited = [[False]*C for _ in range(R)]\n for r in range(R):\n for c in range(C):\n if isInfected[r][c] == 1 and not visited[r][c]:\n clusters.append(getCluster(r,c,visited))\n\n if not clusters:\n return walls\n\n # print(clusters)\n clusters.sort(key=lambda cluster: cluster.numRisked())\n\n # wall off the cluster that threatens the most cells\n walls += clusters[-1].walls\n\n # mark those cells as walled-off for the sake of later getCluster calls\n for (r,c) in clusters[-1].cells:\n isInfected[r][c] = -1\n\n # grow all other clusters\n clusters.pop()\n for cluster in clusters:\n for (r,c) in cluster.risked:\n isInfected[r][c] = 1\n``` | 1 | 0 | ['Python3'] | 0 |
contain-virus | ONE OF THE HARDEST QUESTIONS I EVER SOLVED || DFS || 30 MS || JAVA | one-of-the-hardest-questions-i-ever-solv-ih9h | Code\n\nclass AreaInfo {\n Set<List<Integer>> nodes;\n int id;\n int numExposed;\n\n public AreaInfo(int id) {\n this.nodes = new HashSet<>() | youssef1998 | NORMAL | 2023-06-19T08:38:55.968755+00:00 | 2023-06-19T08:38:55.968797+00:00 | 558 | false | # Code\n```\nclass AreaInfo {\n Set<List<Integer>> nodes;\n int id;\n int numExposed;\n\n public AreaInfo(int id) {\n this.nodes = new HashSet<>();\n this.id = id;\n this.numExposed = 0;\n }\n}\n\nclass Solution {\n private final int HEALTHY = 0, UNHEALTHY = 1, FOUND = 2, CONTAMINATED = 3;\n private final List<Integer[]> directions = List.of(\n new Integer[] {0, 1}, new Integer[] {0, -1},\n new Integer[] {1, 0}, new Integer[] {-1, 0}\n );\n private Set<List<Integer>> exposed = new HashSet<>();\n\n public int containVirus(int[][] isInfected) {\n Map<Integer, AreaInfo> infectedAreas = getInfectedAreas(isInfected);\n int currentArea = infectedAreas.values().stream().sorted((o1, o2) -> o2.numExposed - o1.numExposed)\n .map(i-> i.id).limit(1).findFirst().orElse(-1);\n int numWalls = 0;\n while (currentArea != -1) {\n AreaInfo areaInfo = infectedAreas.get(currentArea);\n List<Integer> start = areaInfo.nodes.stream().limit(1).collect(Collectors.toList()).get(0);\n numWalls += surroundWithWalls(start.get(0), start.get(1), isInfected, 0);\n int finalCurrentArea = currentArea;\n infectedAreas.values().forEach(area-> {\n if(area.id != finalCurrentArea) {\n Set<List<Integer>> initialNodes = new HashSet<>(area.nodes);\n initialNodes.forEach(node -> {\n expandVirus(node.get(0), node.get(1), isInfected, area, 0);\n });\n }\n });\n infectedAreas = getInfectedAreas(isInfected);\n currentArea = infectedAreas.values().stream().sorted((o1, o2) -> o2.numExposed - o1.numExposed)\n .map(i-> i.id).limit(1).findFirst().orElse(-1);\n }\n return numWalls;\n }\n\n private void expandVirus(Integer i, Integer j, int[][] isInfected, AreaInfo areaInfo, int depth) {\n if(isInfected[i][j] == CONTAMINATED) return;\n areaInfo.nodes.add(List.of(i, j));\n isInfected[i][j] = 1;\n for (Integer[] direction: directions) {\n int x = direction[0] + i, y = direction[1] + j;\n if(depth == 0 && isValid(x, y , isInfected) && isInfected[x][y] == HEALTHY)\n expandVirus(x, y, isInfected, areaInfo, depth + 1);\n }\n }\n\n private int surroundWithWalls(int i, int j, int[][] isInfected, int walls) {\n if(isInfected[i][j] == CONTAMINATED) return 0;\n isInfected[i][j] = CONTAMINATED;\n for (Integer[] direction: directions) {\n int x = direction[0] + i, y = direction[1] + j;\n if(isValid(x, y , isInfected) && isInfected[x][y] == HEALTHY) {\n walls++;\n }\n }\n for (Integer[] direction: directions) {\n int x = direction[0] + i, y = direction[1] + j;\n if(isValid(x, y , isInfected) && isInfected[x][y] == FOUND)\n walls = surroundWithWalls(x, y, isInfected, walls);\n }\n return walls;\n }\n\n private Map<Integer, AreaInfo> getInfectedAreas(int[][] isInfected) {\n Map<Integer, AreaInfo> infectedAreas = new HashMap<>();\n int areaId = 0;\n for (int i = 0; i < isInfected.length; i++) {\n for (int j = 0; j < isInfected[0].length; j++) {\n if(isInfected[i][j] == 1) {\n AreaInfo areaInfo = new AreaInfo(areaId);\n exposed = new HashSet<>();\n searchInfected(i, j, isInfected, areaInfo);\n infectedAreas.put(areaInfo.id, areaInfo);\n areaId++;\n }\n }\n }\n return infectedAreas;\n }\n\n private void searchInfected(int i, int j, int[][] isInfected, AreaInfo areaInfo) {\n if(isInfected[i][j] == CONTAMINATED) return;\n areaInfo.nodes.add(List.of(i, j));\n isInfected[i][j] = FOUND;\n for (Integer[] direction: directions) {\n int x = direction[0] + i, y = direction[1] + j;\n if(isValid(x, y , isInfected) && !exposed.contains(List.of(x, y)) && isInfected[x][y] == HEALTHY) {\n areaInfo.numExposed++;\n exposed.add(List.of(x, y));\n }\n }\n for (Integer[] direction: directions) {\n int x = direction[0] + i, y = direction[1] + j;\n if(isValid(x, y , isInfected) && isInfected[x][y] == UNHEALTHY)\n searchInfected(x, y, isInfected, areaInfo);\n }\n }\n\n private boolean isValid(int i, int j, int[][] isInfected) {\n return i >= 0 && i < isInfected.length && j >= 0 && j < isInfected[0].length;\n }\n}\n``` | 1 | 0 | ['Depth-First Search', 'Sorting', 'Matrix', 'Java'] | 0 |
contain-virus | Solution | solution-by-deleted_user-93l6 | C++ []\nint mp[2652], *zp[2652], zc[2652], step, mk;\n\nint dfs(int *p) {\n *p = 2;\n int res = 0;\n for (int *nb : {p-step, p-1, p+1, p+step}) {\n | deleted_user | NORMAL | 2023-04-24T09:17:36.704495+00:00 | 2023-04-24T09:48:24.746491+00:00 | 1,638 | false | ```C++ []\nint mp[2652], *zp[2652], zc[2652], step, mk;\n\nint dfs(int *p) {\n *p = 2;\n int res = 0;\n for (int *nb : {p-step, p-1, p+1, p+step}) {\n int v = *nb;\n if (v == mk || v > 1) continue;\n if (v <= 0) *nb = mk, ++res; else res += dfs(nb);\n }\n return res;\n}\nint dfs2(int *p) {\n *p = 1000;\n int res = 0;\n for (int *nb : {p-step, p-1, p+1, p+step}) {\n int v = *nb;\n if (v == 2) res += dfs2(nb); else if (v <= 0) ++res, *nb = 0;\n }\n return res;\n}\nvoid dfs3(int *p) {\n *p = 1;\n for (int *nb : {p-step, p-1, p+1, p+step}) {\n int v = *nb;\n if (v == 2) dfs3(nb); else if (v <= 0) *nb = 1;\n }\n}\nclass Solution {\npublic:\n int containVirus(vector<vector<int>>& isInfected) {\n step = isInfected[0].size() + 1; mk = 0;\n {\n int *p = mp+step;\n fill(mp, p, 1000);\n for (const auto &r : isInfected) {\n for (int x : r) *p++ = x;\n *p++ = 1000;\n }\n fill(p, p+step, 1000);\n }\n int *lo = mp+step, *hi = lo + step*isInfected.size(), res = 0;\n while(1) {\n int nb = 0;\n for (int *p = lo; p != hi; ++p) if (*p == 1) zp[nb] = p, --mk, zc[nb++] = dfs(p);\n if (nb == 0) break;\n\n int best = 0;\n for (int i = 1; i < nb; ++i) if (zc[i] > zc[best]) best = i;\n if (!zc[best]) break;\n res += dfs2(zp[best]);\n\n for (int *p = lo; p != hi; ++p) if (*p == 2) dfs3(p);\n }\n return res;\n }\n};\n```\n\n```Python3 []\nimport math\n\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n\n def traverse_infected(r,c):\n\n q = [(r,c)]\n infected_cells = set(q)\n perimeter = 0\n bordering_cells = set()\n\n while len(q) > 0:\n next_iter = []\n\n for r,c in q:\n neighbors = [(r+1,c),(r-1,c),(r,c+1),(r,c-1)]\n for adj_r,adj_c in neighbors:\n if m > adj_r >= 0 and n > adj_c >= 0:\n if isInfected[adj_r][adj_c] == 1:\n if (adj_r,adj_c) not in infected_cells:\n infected_cells.add((adj_r,adj_c))\n next_iter.append((adj_r,adj_c))\n elif isInfected[adj_r][adj_c] == 0:\n perimeter += 1\n bordering_cells.add((adj_r,adj_c))\n q = next_iter\n \n return infected_cells,bordering_cells,perimeter\n \n m,n = len(isInfected),len(isInfected[0])\n\n walls = 0\n while 1:\n all_infected_cells = set()\n\n most_threatening = (0, None)\n\n regions_this_iter = []\n i = 0\n for r in range(m):\n for c in range(n):\n if isInfected[r][c] == 1 and (r,c) not in all_infected_cells:\n infected_region,region_borders,perimeter = traverse_infected(r,c)\n\n regions_this_iter.append((infected_region,region_borders,perimeter))\n\n if len(region_borders) > most_threatening[0]:\n most_threatening = (len(region_borders), i)\n \n all_infected_cells.update(infected_region)\n i += 1\n \n if most_threatening[0] != 0:\n walls += regions_this_iter[most_threatening[1]][2]\n for r,c in regions_this_iter[most_threatening[1]][0]:\n isInfected[r][c] = 2\n \n for i in range(len(regions_this_iter)):\n if i != most_threatening[1]:\n for r,c in regions_this_iter[i][1]:\n isInfected[r][c] = 1\n else:\n break\n return walls\n```\n\n```Java []\nclass Solution {\n class Region {\n Set<Integer> infected = new HashSet<>();\n Set<Integer> unInfected = new HashSet<>();\n int walls = 0;\n } \n public int containVirus(int[][] isInfected) {\n int ans = 0;\n int re = isInfected.length;\n int ce = isInfected[0].length;\n\n while (true) {\n List<Region> holder = new ArrayList<>();\n boolean[][] v = new boolean[re][ce];\n for (int r = 0; r < re; r++) {\n for (int c = 0; c < ce; c++) {\n if (isInfected[r][c] == 1 && !v[r][c]) {\n Region region = new Region();\n getRegion(isInfected, region, re, ce, v, r, c);\n holder.add(region);\n }\n }\n }\n int indexOfMaxUnInfected = 0;\n int sizeOfMaxUnInfected = 0;\n for (int i = 0; i < holder.size(); i++) {\n Region region = holder.get(i);\n\n if (region.unInfected.size() > sizeOfMaxUnInfected) {\n sizeOfMaxUnInfected = region.unInfected.size();\n indexOfMaxUnInfected = i;\n }\n }\n if (holder.size() == 0) {\n break;\n }\n Set<Integer> maxSet = holder.get(indexOfMaxUnInfected).infected;\n for (int rowCol : maxSet) {\n int r = rowCol / ce;\n int c = rowCol % ce;\n isInfected[r][c] = 2;\n }\n ans += holder.get(indexOfMaxUnInfected).walls;\n for (int i = 0; i < holder.size(); i++) {\n \n if (i == indexOfMaxUnInfected) {\n continue;\n }\n Region region = holder.get(i);\n Set<Integer> unInfected = region.unInfected;\n\n for (int rowCol : unInfected) {\n int r = rowCol / ce;\n int c = rowCol % ce;\n isInfected[r][c] = 1;\n }\n }\n }\n return ans;\n }\n int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n private void getRegion(int[][] isInfected, Region region, int re, int ce, \n boolean[][] v, int r, int c) {\n if (r < 0 || c < 0 || r == re || c == ce || isInfected[r][c] == 2) {\n return;\n }\n if (isInfected[r][c] == 1) {\n if (v[r][c]) {\n return;\n }\n region.infected.add(r * ce + c);\n }\n if (isInfected[r][c] == 0) {\n region.unInfected.add(r * ce + c);\n region.walls++;\n return;\n }\n v[r][c] = true;\n for (int[] dir : dirs) {\n int nr = r + dir[0];\n int nc = c + dir[1];\n getRegion(isInfected, region, re, ce, v, nr, nc);\n }\n }\n}\n```\n | 1 | 0 | ['C++', 'Java', 'Python3'] | 0 |
contain-virus | DFS + Heap | dfs-heap-by-bbblair-256c | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n # isInfected: 0 for uninfected; 1 for infected; -1 for contained;\n | bbblair | NORMAL | 2022-09-30T22:35:26.421635+00:00 | 2022-09-30T22:35:26.421668+00:00 | 128 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n # isInfected: 0 for uninfected; 1 for infected; -1 for contained;\n # use DFS to traverse the whole board to find \n # - the infected area (any cell);\n # - its risky cells;\n # - the number of walls needed to contain it\n # make the risky cells array a heap:\n # - single out the area with max risky cells\n # - mark the rest of the risky cell infected\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n\n # return number of walls needed\n def dfs(r, c):\n\n # return\n if (r, c) in visited or r < 0 or c < 0 or r >= m or c >= n:\n return 0\n\n # contained cells\n if isInfected[r][c] == -1:\n return 0\n \n # uninfected cells\n if isInfected[r][c] == 0:\n risky.add((r, c))\n return 1\n \n # infected cells\n visited.add((r ,c))\n walls = 0\n if isInfected[r][c] == 1:\n walls += dfs(r+1, c)\n walls += dfs(r-1, c)\n walls += dfs(r, c+1)\n walls += dfs(r, c-1)\n\n return walls\n \n m, n = len(isInfected), len(isInfected[0])\n total_wall = 0\n\n while True:\n # store (len(risky), risky, wall, starting points)\n gettingInfected = []\n visited = set()\n for i in range(m):\n for j in range(n):\n if isInfected[i][j] == 1 and isInfected[i][j] not in visited:\n risky = set()\n w = dfs(i, j)\n gettingInfected.append((-len(risky), risky, w, i, j))\n\n \n # heapy the gettingInfectious array to get the max len of risky\n heapq.heapify(gettingInfected)\n\n if not gettingInfected or gettingInfected[0][2] == 0:\n return total_wall\n\n # mark the infected cells as contained starting from (i, j)\n lr, risky, w, i, j = heapq.heappop(gettingInfected)\n # maybe a dfs for marking the cells?\n queue = collections.deque([(i, j)])\n while queue:\n r, c = queue.pop()\n if r < 0 or c < 0 or r >= m or c >= n or isInfected[r][c] != 1:\n continue\n\n isInfected[r][c] = -1\n\n queue.append((r+1, c))\n queue.append((r-1, c))\n queue.append((r, c+1))\n queue.append((r, c-1))\n\n # increment the total walls\n total_wall += w\n for area in gettingInfected:\n riskyCells = area[1]\n for cell in riskyCells:\n r, c = cell\n isInfected[r][c] = 1\n\n``` | 1 | 1 | ['Python3'] | 0 |
contain-virus | DFS with "marker" , 15 ms | dfs-with-marker-15-ms-by-mrn3088-6xp7 | This problem is just a simulation.\nThe whole process is:\n1. Find which group of virus would infect most uninfected area. If no group of virus could infect mor | mrn3088 | NORMAL | 2022-07-18T07:54:05.557765+00:00 | 2022-07-18T07:54:05.557812+00:00 | 578 | false | This problem is just a simulation.\nThe whole process is:\n1. Find which group of virus would infect most uninfected area. If no group of virus could infect more uninfected area, break.\n2. Deactive that group of virus.\n3. Let the rest group of virus spread.\nWe could use dfs to implement 1, 2, and 3. \nThe trickest part is to determine how many uninfected grid would a group of virus would infect in this round. \nIn case: \n1 0 \n1 1\n0 might be visited three times, however it should only appears once. If we simply use a "visited" array to memorize, the following case might happpen:\n1 0 1 0\n1 0 1 0\nDfs on the left group of virus would make the two 0 been "visited", but the right group needs to count these two 0 in its "infected number". If we do a memset for the whole "visited" array after each dfs call, it might cause TLE. \n\nSo we could use a marker to mark the "visited" array. Each dfs call would use a different marker, and the dfs would stop only when current marker == marker that marked the visited array.\n\n```\n#include <bits/stdc++.h>\nusing namespace std;\nint visited[51][51];\nint fx[] = {1, 0, -1, 0};\nint fy[] = {0, 1, 0, -1};\nclass Solution {\npublic:\n\tint m, n;\n\tbool valid(int i, int j) {\n\t\treturn i >= 0 && j >= 0 && i < m && j < n;\n\t}\n\n\tint dfs(int i, int j, vector<vector<int>>& isInfected, int marker) {\n\t\tif (!valid(i, j) || visited[i][j] || isInfected[i][j] != 1) return 0;\n\t\tvisited[i][j] = 1;\n\t\tint cnt = 0;\n\t\tfor (int k = 0; k < 4; k++) {\n\t\t\tint x = i + fx[k], y = j + fy[k];\n\t\t\tif (!valid(x, y)) continue;\n\t\t\tif (isInfected[x][y] == 0 && visited[x][y] != marker) {\n\t\t\t\tcnt++;\n\t\t\t\tvisited[x][y] = marker;\n\t\t\t} else if (isInfected[x][y] == 1) {\n\t\t\t\tcnt += dfs(x, y, isInfected, marker);\n\t\t\t}\n\t\t}\n\t\treturn cnt;\n\t}\n\n\tint buildWall(int i, int j, vector<vector<int>>& isInfected) {\n\t\tint cnt = 0;\n\t\tisInfected[i][j] = -1;\n\t\tfor (int k = 0; k < 4; k++) {\n\t\t\tint x = i + fx[k], y = j + fy[k];\n\t\t\tif (!valid(x, y)) continue;\n\t\t\tif (isInfected[x][y] == 1) {\n\t\t\t\tcnt += buildWall(x, y, isInfected);\n\t\t\t} else if (isInfected[x][y] == 0) {\n\t\t\t\tcnt++;\n\t\t\t}\n\t\t}\n\t\treturn cnt;\n\t}\n\n\tvoid spread(vector<vector<int>>& isInfected) {\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\tif (isInfected[i][j] != 0) continue;\n\t\t\t\tbool infect = 0;\n\t\t\t\tfor (int k = 0; k < 4; k++) {\n\t\t\t\t\tint x = i + fx[k], y = j + fy[k];\n\t\t\t\t\tif (valid(x, y) && isInfected[x][y] == 1) {\n\t\t\t\t\t\tinfect = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (infect) isInfected[i][j] = -2;\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\tif (isInfected[i][j] == -2) {\n\t\t\t\t\tisInfected[i][j] = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tvoid print(vector<vector<int>>& isInfected) {\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\tcout << isInfected[i][j] << " ";\n\t\t\t}\n\t\t\tcout << endl;\n\t\t}\n\t\t\t\n\t}\n int containVirus(vector<vector<int>>& isInfected) {\n\t\tint res = 0;\n\t\tm = isInfected.size();\n\t\tn = isInfected[0].size();\n while (true) {\n\t\t\tmemset(visited, 0, sizeof(visited));\n\t\t\tint cx = -1, cy = -1, cv = 0;\n\t\t\tint hasGood = 0, marker = 4;\n\t\t\tfor (int i = 0; i < m; i++) {\n\t\t\t\tfor (int j = 0; j < n; j++) {\n hasGood = hasGood || isInfected[i][j] == 0;\n if (isInfected[i][j] != 1) continue;\n\t\t\t\t\tint tmp = dfs(i, j, isInfected, marker++);\n\t\t\t\t\tif (tmp > cv) {\n\t\t\t\t\t\tcv = tmp;\n\t\t\t\t\t\tcx = i;\n\t\t\t\t\t\tcy = j;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!cv || !hasGood) break;\n\t\t\tres += buildWall(cx, cy, isInfected);\n\t\t\tspread(isInfected);\n\t\t}\n\t\treturn res;\n\n }\n};\n``` | 1 | 0 | ['Depth-First Search', 'Simulation'] | 0 |
contain-virus | Infinite Grid? DSU & DFS [Modular w/ Diagram] | infinite-grid-dsu-dfs-modular-w-diagram-marfe | General Idea\n\n- If the board is huge, we\'d want to avoid traverse it every time to process everything. \n [My solution will work even if the grid is infinit | Student2091 | NORMAL | 2022-06-19T09:26:37.752003+00:00 | 2022-06-22T07:09:53.760126+00:00 | 510 | false | **General Idea**\n\n- If the board is huge, we\'d want to avoid traverse it every time to process everything. \n *[My solution will work even if the grid is infinitely large as long as we are given a list of virus coordinates.]*\n\n- There is a way to do that - *Union Find* - we can traverse the board 1 time to get all the virus\'s group. \nAnd from there, we do multi source DFS **outward from the virus borders** 1 step per loop. \nAny cell visitied will be marked as visited **because there is no reason to traverse inward.**\nThis way, we only traverse the board **at worst 2 times, at best 1 time, and if we are given virus coordinates, it\'d be at best 0 time.**\n\n- In order to know which group the virus is it, we will assign a group ID to them.\nThe root of each virus group is what we will be using to determined the number of walls and clean cells around it.\n</br>\n\n**Some Details**\n- To track the number of clean cells, we use `i*n+j` as the id for `isInfected[i][j]` along with a HashSet.\n\n- Virus Group ID begins at 2 because 0 and 1 are used by `isInfected[][]` already.\n\n- VIRUS (=1) means a pending virus (that is about to get explored) with no group assigned to it.\n\n- Walled virus will not be explored from other alive, spreading virus.\n\n- Do not kill (set to null) any alive virus that is not the root of the group because other groups of virus may union it.\n</br>\n\n**Simulation (Diagram)**\nTake this testcase for example:\n```\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 1, 0, 0]\n[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 1, 0, 0, 0, 1, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 1, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, 1, 0]\n[0, 0, 0, 0, 1, 0, 1, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n```\nIt will be processed like so:\n```\nSTART: \n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 2, 0, 0]\n[3, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 4, 0, 0, 0, 5, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 5, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, 6, 0]\n[0, 0, 0, 0, 7, 0, 8, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n------------------------------\n\nVirus Group 5 Walled.\n# of Clean Cells: 6\nWalls Gained: 6\nCurrent ans: 6\n\nVirus Group 4 and 3 United.\nVirus Group 8 and 6 United.\nVirus Group 8 and 7 United.\n\nCurrent board: \n[0, 0, 0, 0, 0, 0, 0, 2, 0, 0]\n[3, 0, 0, 0, 0, 0, 2, 2, 2, 0]\n[3, 4, 4, 0, 0, 0, 0, 2, 0, 0]\n[4, 4, 4, 4, 0, 0, 5, 0, 0, 0]\n[0, 0, 4, 0, 0, 0, 5, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, 6, 0]\n[0, 0, 0, 0, 7, 0, 8, 8, 6, 6]\n[0, 0, 0, 7, 7, 8, 8, 8, 8, 0]\n[0, 0, 0, 0, 7, 0, 8, 0, 0, 0]\n------------------------------\n\nVirus Group 6 Walled.\n# of Clean Cells: 13\nWalls Gained: 23\nCurrent ans: 29\n\n\nCurrent board: \n[3, 0, 0, 0, 0, 0, 2, 2, 2, 0]\n[3, 3, 3, 0, 0, 2, 2, 2, 2, 2]\n[3, 4, 4, 3, 0, 0, 2, 2, 2, 0]\n[4, 4, 4, 4, 3, 0, 5, 2, 0, 0]\n[3, 3, 4, 3, 0, 0, 5, 0, 0, 0]\n[0, 0, 3, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, 6, 0]\n[0, 0, 0, 0, 7, 0, 8, 8, 6, 6]\n[0, 0, 0, 7, 7, 8, 8, 8, 8, 0]\n[0, 0, 0, 0, 7, 0, 8, 0, 0, 0]\n------------------------------\n\nVirus Group 3 Walled.\n# of Clean Cells: 10\nWalls Gained: 16\nCurrent ans: 45\n\n\nCurrent board: \n[3, 0, 0, 0, 0, 2, 2, 2, 2, 2]\n[3, 3, 3, 0, 2, 2, 2, 2, 2, 2]\n[3, 4, 4, 3, 0, 2, 2, 2, 2, 2]\n[4, 4, 4, 4, 3, 0, 5, 2, 2, 0]\n[3, 3, 4, 3, 0, 0, 5, 2, 0, 0]\n[0, 0, 3, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, 6, 0]\n[0, 0, 0, 0, 7, 0, 8, 8, 6, 6]\n[0, 0, 0, 7, 7, 8, 8, 8, 8, 0]\n[0, 0, 0, 0, 7, 0, 8, 0, 0, 0]\n------------------------------\n\nVirus Group 2 Walled.\n# of Clean Cells: 7\nWalls Gained: 11\nCurrent ans: 56\n\n\nCurrent board: \n[3, 0, 0, 0, 0, 2, 2, 2, 2, 2]\n[3, 3, 3, 0, 2, 2, 2, 2, 2, 2]\n[3, 4, 4, 3, 0, 2, 2, 2, 2, 2]\n[4, 4, 4, 4, 3, 0, 5, 2, 2, 0]\n[3, 3, 4, 3, 0, 0, 5, 2, 0, 0]\n[0, 0, 3, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, 6, 0]\n[0, 0, 0, 0, 7, 0, 8, 8, 6, 6]\n[0, 0, 0, 7, 7, 8, 8, 8, 8, 0]\n[0, 0, 0, 0, 7, 0, 8, 0, 0, 0]\n------------------------------\nDone\n```\n\nBelow, I use PriorityQueue to make things simple. We can also use a HashSet and track the max element. \nTreeSet, on the other hand, is quite difficult to make it work for this problem.\n```Java\nclass Solution {\n int m, n;\n int VIRUS = 1;\n int ID = 2;\n public int containVirus(int[][] isInfected) {\n m = isInfected.length;\n n = isInfected[0].length;\n int ans = 0;\n Comparator<Virus> comp = Comparator.comparingInt(o -> -o.border.size());\n PriorityQueue<Virus> maxheap = new PriorityQueue<>(comp);\n for (int i = 0; i < m; i++){\n for (int j = 0; j < n; j++){\n if (isInfected[i][j]==VIRUS){ // mark all virus cells as visited and populate all groups\n Set<Integer> border = new HashSet<>();\n int id = maxheap.size()+ID;\n int walls = mark(i, j, id, isInfected, border, null, null);\n maxheap.offer(new Virus(id, walls, border));\n }\n }\n }\n\n Virus[] virus = new Virus[maxheap.size()+ID]; // lookup virus by ID\n UF uf = new UF(virus.length); // union find\n\n while(!maxheap.isEmpty()){ // loop until no more virus group\n Virus killed = maxheap.poll();\n ans += killed.walls;\n virus[killed.id]=null; // kill this virus\n PriorityQueue<Virus> next = new PriorityQueue<>(comp);\n for (Virus v : maxheap){\n for (int p : v.border){\n isInfected[p/n][p%n]=VIRUS; // new turn starts, all boarders are now virus\n }\n }\n for (Virus v : maxheap){ // populate the next border and wall count, and union virus groups (if any)\n int walls = 0;\n Set<Integer> nb = new HashSet<>();\n for (int p : v.border){\n walls += mark(p/n, p%n, v.id, isInfected, nb, uf, virus);\n }\n virus[v.id]=new Virus(v.id, walls, nb);\n }\n for (int i = ID; i < virus.length; i++){ // let the root of the virus have it all, and reset the rest\n if (isAliveVirus(i, uf, virus) && !uf.isRoot(i)){\n virus[uf.find(i)].walls+=virus[i].walls;\n virus[uf.find(i)].border.addAll(virus[i].border);\n virus[i] = new Virus(i, 0, new HashSet<>());\n }\n }\n for (int i = ID; i < virus.length; i++){ // enqueue the root virus for the next round.\n if (isAliveVirus(i, uf, virus) && uf.isRoot(i)){\n next.offer(virus[i]);\n }\n }\n maxheap = next;\n }\n\n return ans;\n }\n\n private boolean isAliveVirus(int id, UF uf, Virus[] virus){\n return virus[uf.find(id)]!=null;\n }\n\n private boolean isVirus(int id){\n return id >= ID;\n }\n\n private boolean isDeadVirus(int id, UF uf, Virus[] virus){\n return isVirus(id) && !isAliveVirus(id, uf, virus);\n }\n\n private int mark(int i, int j, int id, int[][] grid, Set<Integer> border, UF uf, Virus[] virus){\n if (i < 0 || j < 0 || i == m || j == n || grid[i][j]==id || isDeadVirus(grid[i][j], uf, virus))\n return 0;\n if (isVirus(grid[i][j])){ // union another virus group and exit\n uf.union(grid[i][j], id);\n return 0;\n }\n if (grid[i][j]==0){\n border.add(i*n+j);\n return 1;\n }\n grid[i][j]=id;\n return mark(i+1, j, id, grid, border, uf, virus)\n + mark(i-1, j, id, grid, border, uf, virus)\n + mark(i, j+1, id, grid, border, uf, virus)\n + mark(i, j-1, id, grid, border, uf, virus);\n }\n\n private class Virus {\n int id;\n int walls;\n Set<Integer> border;\n Virus(int id, int walls, Set<Integer> border){\n this.id = id;\n this.walls = walls;\n this.border = border;\n }\n Virus(){}\n }\n\n private class UF {\n int[] parent;\n int[] rank;\n UF (int n){\n parent = IntStream.range(0, n).toArray();\n rank = new int[n];\n }\n\n private int find(int x){\n return x == parent[x]? x : (parent[x]=find(parent[x]));\n }\n\n private boolean isRoot(int x){\n return x == parent[x];\n }\n\n private void union(int x, int y){\n x = find(x);\n y = find(y);\n if (x==y)\n return;\n if (rank[x]>rank[y]){\n parent[y]=x;\n }else{\n parent[x]=y;\n if (rank[x]==rank[y]){\n rank[y]++;\n }\n }\n }\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
contain-virus | C++| DFS+DSU | c-dfsdsu-by-kumarabhi98-byin | \nclass Solution {\npublic:\n int n,m;\n int d[4][2] = {{0,1},{1,0},{-1,0},{0,-1}};\n int find(vector<int>& nums,int i){\n if(nums[i]==-1) retur | kumarabhi98 | NORMAL | 2022-06-09T14:09:21.025934+00:00 | 2022-06-09T14:09:21.025967+00:00 | 549 | false | ```\nclass Solution {\npublic:\n int n,m;\n int d[4][2] = {{0,1},{1,0},{-1,0},{0,-1}};\n int find(vector<int>& nums,int i){\n if(nums[i]==-1) return i;\n else return nums[i] = find(nums,nums[i]);\n }\n void union_(vector<int>& nums,int x,int y){\n int i = find(nums,x), j = find(nums,y);\n if(i!=j){\n if(i<j) nums[j] = i;\n else nums[i] = j;\n }\n }\n int dfs(vector<vector<int>>& nums,int i,int j){ // returns no. of wall arround the infected region\n if(nums[i][j]==0) return 1;\n nums[i][j] = 2;\n int re = 0;\n for(int k = 0; k<4;++k){\n int x = i+d[k][0], y = j+d[k][1];\n if(!(x<0||x>=n||y<0||y>=m) && nums[x][y]!=2) re+=dfs(nums,x,y);\n }\n return re;\n }\n int dfs2(vector<vector<int>>& nums,vector<int>& dp,int p){ // returns no. of blocks going to infect in next 1 sec.\n int re = 0;\n for(int i = 0; i<n;++i){\n for(int j = 0; j<m; ++j){\n if(nums[i][j]!=0) continue;\n for(int k = 0; k<4;++k){\n int x = i+d[k][0], y = j+d[k][1];\n if(!(x<0||x>=n||y<0||y>=m) && nums[x][y]==1 && p==find(dp,x*m+y)){\n re++; break;\n }\n }\n }\n }\n return re;\n }\n int containVirus(vector<vector<int>>& nums) {\n n = nums.size(), m = nums[0].size();\n vector<int> dp(n*m+1,-1);\n for(int i = 0; i<n;++i){ // union all adjacent infected region\n for(int j = 0; j<m; ++j){\n if(nums[i][j]!=1) continue;\n for(int k = 0; k<4;++k){\n int x = i+d[k][0], y = j+d[k][1];\n if(!(x<0||x>=n||y<0||y>=m) && nums[x][y]==1)\n union_(dp,i*m+j,x*m+y);\n }\n }\n }\n int re = 0;\n while(1){\n int p = -1,max_ = -1;\n for(int k = 0; k<n*m;++k){ // find the region going to infect maximum uninfected region in next 1 sec.\n int i = k/m; int j = k-i*m;\n if(dp[k]==-1 && nums[i][j]==1){\n int t = dfs2(nums,dp,k); // no. of uninfected going to infect in next 1 sec by some infect whose parent node if k.\n if(t>max_){\n max_ = t; p = k;\n }\n }\n }\n if(p==-1) break; // break if there are no blocks to infect\n int i = p/m; int j = p-i*m;\n int tre = dfs(nums,i,j); // no. of wall\n re+=tre;\n vector<pair<int,int>> temp;\n for(int i = 0; i<n;++i){ // infect the uninfected region in next sec.\n for(int j = 0;j<m;++j){\n if(nums[i][j]!=0) continue;\n bool is= 0;\n for(int k = 0; k<4;++k){\n int x = i+d[k][0], y = j+d[k][1];\n if(!(x<0||x>=n||y<0||y>=m) && nums[x][y]==1) {is = 1; break;}\n }\n if(is) temp.push_back({i,j});\n }\n }\n for(int i = 0; i<temp.size();++i) nums[temp[i].first][temp[i].second] = 1; \n for(int k = 0; k<temp.size(); ++k){ // union newly infected cells to there adjacent\n int i = temp[k].first, j = temp[k].second;\n for(int l = 0; l<4;++l){\n int x = i+d[l][0], y = j+d[l][1];\n if(!(x<0||x>=n||y<0||y>=m) && nums[x][y]==1) union_(dp,i*m+j,x*m+y);\n } \n }\n }\n return re;\n }\n};\n// Try for larger TestCase\n// [[0,0,1,1,1,0,1,0,0,0],[1,1,1,0,0,0,1,1,0,1],[0,0,0,0,0,0,1,0,0,0],[0,0,0,0,1,0,1,0,0,0],[1,0,0,0,1,1,1,0,0,0],[0,0,0,1,0,1,1,0,0,0],[1,0,0,0,0,1,0,0,0,1],[1,0,0,0,0,0,0,0,0,1],[0,1,0,0,0,0,0,0,1,0],[1,1,0,0,0,1,0,1,0,0]]\n\n``` | 1 | 0 | ['Depth-First Search', 'C'] | 0 |
contain-virus | ✅ C++ | CLEAN CODE | BFS | c-clean-code-bfs-by-akshitasinghal-7gpx | \nclass Solution {\npublic:\n int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};\n int walls=0;\n \n bool isValid(int i,int j,int m,int n,vector<vector<int>> &v | akshitasinghal | NORMAL | 2022-03-25T10:53:38.038563+00:00 | 2022-03-25T10:53:38.038602+00:00 | 852 | false | ```\nclass Solution {\npublic:\n int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};\n int walls=0;\n \n bool isValid(int i,int j,int m,int n,vector<vector<int>> &vis)\n {\n return (i>=0 && i<m && j>=0 && j<n && !vis[i][j]); \n }\n \n int find(int i,int j,int m,int n,vector<vector<int>>& a)\n {\n int c=0;\n \n queue<pair<int,int>> q;\n vector<vector<int>> vis(m,vector<int>(n,0));\n \n a[i][j]=2;\n q.push({i,j});\n \n while(!q.empty())\n {\n i=q.front().first;\n j=q.front().second;\n q.pop();\n \n for(int k=0;k<4;k++)\n {\n if(isValid(i+dx[k],j+dy[k],m,n,vis))\n {\n if(a[i+dx[k]][j+dy[k]]==0)\n c++;\n else if(a[i+dx[k]][j+dy[k]]==1)\n {\n a[i+dx[k]][j+dy[k]]=2;\n q.push({i+dx[k],j+dy[k]});\n }\n \n vis[i+dx[k]][j+dy[k]]=1;\n \n }\n }\n }\n \n return c;\n }\n \n void putwalls(pair<int,int> &change,int m,int n,vector<vector<int>>& a)\n {\n int i,j;\n i=change.first;\n j=change.second;\n \n queue<pair<int,int>> q;\n vector<vector<int>> vis(m,vector<int>(n,0));\n \n q.push({i,j});\n \n while(!q.empty())\n {\n i=q.front().first;\n j=q.front().second;\n a[i][j]=-1;\n q.pop();\n \n \n for(int k=0;k<4;k++)\n {\n if(isValid(i+dx[k],j+dy[k],m,n,vis))\n {\n if(a[i+dx[k]][j+dy[k]]==2)\n {\n q.push({i+dx[k],j+dy[k]});\n a[i+dx[k]][j+dy[k]]=-1;\n vis[i+dx[k]][j+dy[k]]=1; \n } \n else if(a[i+dx[k]][j+dy[k]]==0)\n walls++;\n }\n }\n }\n }\n \n void spread(int m,int n,vector<vector<int>>& a)\n {\n int i,j;\n queue<pair<int,int>> q;\n vector<vector<int>> vis(m,vector<int>(n,0));\n \n for(i=0;i<m;i++)\n {\n for(j=0;j<n;j++)\n {\n if(a[i][j]==2)\n {\n a[i][j]=1;\n q.push({i,j});\n\n }\n }\n }\n \n while(!q.empty())\n {\n i=q.front().first;\n j=q.front().second;\n q.pop();\n \n for(int k=0;k<4;k++)\n {\n if(isValid(i+dx[k],j+dy[k],m,n,vis) && a[i+dx[k]][j+dy[k]]==0)\n {\n a[i+dx[k]][j+dy[k]]=1;\n vis[i+dx[k]][j+dy[k]]=1; \n }\n }\n }\n }\n \n int containVirus(vector<vector<int>>& a) {\n int m=a.size(),n=a[0].size();\n int i,j;\n \n int infected=INT_MIN;\n pair<int,int> change;\n \n while(infected!=0)\n {\n infected=0;\n for(i=0;i<m;i++)\n {\n for(j=0;j<n;j++)\n {\n if(a[i][j]==1)\n {\n int x=find(i,j,m,n,a);\n if(x>infected)\n {\n change={i,j};\n infected=x;\n }\n }\n }\n }\n \n if(infected!=0)\n {\n putwalls(change,m,n,a);\n spread(m,n,a);\n }\n }\n \n return walls;\n }\n};\n```\n\n**Do share your views & upvote if you like !!!** \uD83D\uDE0A | 1 | 0 | ['Breadth-First Search', 'C', 'C++'] | 1 |
contain-virus | Unable to find issue in code. Failing test case added | unable-to-find-issue-in-code-failing-tes-jzen | \nclass Solution {\n public int containVirus(int[][] isInfected) {\n int m = isInfected.length;\n int n = isInfected[0].length;\n int[] | akshay82 | NORMAL | 2022-03-02T02:27:14.728566+00:00 | 2022-03-02T02:27:14.728593+00:00 | 116 | false | ```\nclass Solution {\n public int containVirus(int[][] isInfected) {\n int m = isInfected.length;\n int n = isInfected[0].length;\n int[] dx = {0, 0, 1, -1};\n int[] dy = {1, -1, 0, 0};\n int total = 0;\n int count = 0;\n int maxWalls = 0;\n print(isInfected, m, n);\n do {\n DSU dsu = new DSU(m*n);\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (isInfected[i][j] == 1) {\n for (int k = 0; k < 4; k++) {\n int x = i + dx[k];\n int y = j + dy[k];\n if (isInBorder(m, n, x, y) && isInfected[x][y] == 1) {\n dsu.unionBySize(i*n + j, x*n + y);\n }\n }\n }\n } \n }\n Map<Integer, List<int[]>> components = new HashMap<>();\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (isInfected[i][j] == 1) {\n int group = dsu.findRepresentative(i*n + j);\n if (!components.containsKey(group)) {\n components.put(group, new ArrayList<>());\n }\n components.get(group).add(new int[]{i, j});\n }\n }\n }\n maxWalls = 0;\n int surroundGroup = 0;\n for (Map.Entry<Integer, List<int[]>> entry : components.entrySet()) {\n int walls = 0;\n List<int[]> cells = entry.getValue();\n for (int[] cell : cells) {\n for (int k = 0; k < 4; k++) {\n int x = cell[0] + dx[k];\n int y = cell[1] + dy[k];\n if (isInBorder(m, n, x, y) && isInfected[x][y] == 0) {\n walls++;\n }\n } \n }\n if (maxWalls < walls) {\n surroundGroup = entry.getKey();\n maxWalls = walls;\n }\n }\n if (maxWalls == 0) {\n break;\n }\n System.out.println("maxWalls " + maxWalls);\n total += maxWalls;\n List<int[]> cellsToBlock = components.get(surroundGroup);\n for (int[] cell : cellsToBlock) {\n isInfected[cell[0]][cell[1]] = -1;\n }\n System.out.println("surroundGroup " + surroundGroup);\n System.out.println("keys " + components.keySet());\n components.remove(surroundGroup);\n for (List<int[]> cells : components.values()) {\n for (int[] cell : cells) {\n for (int k = 0; k < 4; k++) {\n int x = cell[0] + dx[k];\n int y = cell[1] + dy[k];\n if (isInBorder(m, n, x, y)) {\n isInfected[x][y] = 1;\n }\n } \n }\n }\n print(isInfected, m, n);\n } while(true);\n return total;\n }\n \n void print(int[][] isInfected, int m, int n) {\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n System.out.print(" " + isInfected[i][j]);\n }\n System.out.println();\n }\n }\n \n boolean isInBorder(int m, int n, int x, int y) {\n if (x >=0 && y>=0 && x<m && y< n) {\n return true;\n }\n return false;\n }\n}\n\n\nclass DSU {\n int representative [];\n int size [];\n \n DSU(int sz) {\n representative = new int[sz];\n size = new int[sz];\n \n for (int i = 0; i < sz; ++i) {\n // Initially each group is its own representative\n representative[i] = i;\n // Intialize the size of all groups to 1\n size[i] = 1;\n }\n }\n \n // Finds the representative of group x\n public int findRepresentative(int x) {\n if (x == representative[x]) {\n return x;\n }\n \n // This is path compression\n return representative[x] = findRepresentative(representative[x]);\n }\n \n // Unite the group that contains "a" with the group that contains "b"\n public void unionBySize(int a, int b) {\n int representativeA = findRepresentative(a);\n int representativeB = findRepresentative(b);\n \n // If nodes a and b already belong to the same group, do nothing.\n if (representativeA == representativeB) {\n return;\n }\n \n // Union by size: point the representative of the smaller\n // group to the representative of the larger group.\n if (size[representativeA] >= size[representativeB]) {\n size[representativeA] += size[representativeB];\n representative[representativeB] = representativeA;\n } else {\n size[representativeB] += size[representativeA];\n representative[representativeA] = representativeB;\n }\n }\n}\n```\n\nTest case which is failing:\n[[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,1,0,0],[1,0,0,0,0,0,0,0,0,0],[0,0,1,0,0,0,1,0,0,0],[0,0,0,0,0,0,1,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,1,0],[0,0,0,0,1,0,1,0,0,0],[0,0,0,0,0,0,0,0,0,0]] | 1 | 0 | [] | 0 |
contain-virus | C++ DFS solution, Easy Understand. | c-dfs-solution-easy-understand-by-dxw199-c2rg | ```c++\nclass Solution {\n \n int M, N;\n \n //marking those cells as -1\n void buildWall(vector>& fec, int r, int c){\n //if it is alread | dxw1997 | NORMAL | 2021-11-01T11:09:58.263523+00:00 | 2021-11-01T11:09:58.263562+00:00 | 575 | false | ```c++\nclass Solution {\n \n int M, N;\n \n //marking those cells as -1\n void buildWall(vector<vector<int>>& fec, int r, int c){\n //if it is already marked or empty, just return.\n if(r < 0 || c < 0 || r >= M || c >= N || fec[r][c] <= 0) return;\n fec[r][c] = -1;//mark this cell.\n buildWall(fec, r-1, c);\n buildWall(fec, r, c-1);\n buildWall(fec, r+1, c);\n buildWall(fec, r, c+1);\n return;\n }\n //the returning parameter is the number of walls you need to build.\n int calcWalls(vector<vector<int>>& fec, vector<vector<bool>>& vis, int r, int c, unordered_set<int>& ca){\n if(r < 0 || c < 0 || r >= fec.size() || c >= fec[0].size() || vis[r][c] || fec[r][c] < 0) return 0;\n if(fec[r][c] == 0){\n ca.insert(r*N+c);//a possible expand position\n return 1;//you need to build a wall here\n }\n vis[r][c] = true;\n return calcWalls(fec, vis, r-1, c, ca) + calcWalls(fec, vis, r+1, c, ca) + calcWalls(fec, vis, r, c-1, ca) + \n calcWalls(fec, vis, r, c+1, ca);\n }\n \npublic:\n int containVirus(vector<vector<int>>& isInfected) {\n this->M = isInfected.size(), this->N = isInfected[0].size();\n int res = 0, indx = 0;//indx is a candidate block position.\n while(indx != -1){\n vector<vector<bool>> vis(M, vector<bool>(N));\n int needbuildwalls = 0, msize = 0;\n indx = -1;\n unordered_map<int, unordered_set<int>> conta;//for storing the threatened cells for (i,j) = i*N+j\n for(int i = 0;i < M;++i ){\n for(int j = 0;j < N;++j ){\n if(!vis[i][j] && isInfected[i][j] == 1){\n int tmp = calcWalls(isInfected, vis, i, j, conta[i*N+j]);\n if(conta[i*N+j].size() > msize){//updating the candidate position.\n needbuildwalls = tmp;\n msize = conta[i*N+j].size();\n indx = i*N+j;\n }\n }\n }//for\n }//for\n res += needbuildwalls;\n if(indx >= 0) buildWall(isInfected, indx/N, indx%N);\n //the virus spreads to all neighboring cells\n for(auto iter = conta.begin();iter != conta.end();++iter){\n if(iter->first != indx){\n for(int pos:iter->second){\n isInfected[pos/N][pos%N] = 1;//marked as 1\n }\n }\n }\n }//while\n return res;\n }\n};\n | 1 | 0 | [] | 0 |
contain-virus | java no brain approach | java-no-brain-approach-by-jjyz-9mdu | ```\nclass Solution {\n class Info{\n int wallsToBuild;\n Set threatenArea;\n Set origArea;\n public Info(int x, Set threatenArea | JJYZ | NORMAL | 2020-08-03T03:13:32.981959+00:00 | 2020-08-03T03:13:32.982007+00:00 | 497 | false | ```\nclass Solution {\n class Info{\n int wallsToBuild;\n Set<Integer> threatenArea;\n Set<Integer> origArea;\n public Info(int x, Set<Integer> threatenArea, Set<Integer> origArea){\n this.wallsToBuild = x;\n this.threatenArea = threatenArea;\n this.origArea = origArea;\n }\n }\n int res = 0;\n public int containVirus(int[][] grid) {\n int rows = grid.length;\n int cols = grid[0].length;\n PriorityQueue<Info> threatenAreas = new PriorityQueue<Info>((a,b)->b.threatenArea.size()-a.threatenArea.size());\n for(int i=0; i<rows; i++){\n for(int j=0; j<cols; j++){\n if(grid[i][j] == 1){\n Set<Integer> threatenArea = new HashSet();\n Set<Integer> origArea = new HashSet();\n int wallsToBuild = dfs(i, j, grid, threatenArea, origArea);\n if(threatenArea.size()>0)\n threatenAreas.offer(new Info(wallsToBuild, threatenArea, origArea));\n }\n }\n }\n if(threatenAreas.isEmpty()) return res;\n Info largestArea = threatenAreas.poll();\n res += largestArea.wallsToBuild;\n buildWalls(largestArea.origArea, grid);\n while(!threatenAreas.isEmpty()){\n Info nextArea = threatenAreas.poll();\n Set<Integer> origThreatenArea = nextArea.threatenArea;\n Set<Integer> newArea = new HashSet();\n Iterator<Integer> iter = origThreatenArea.iterator();\n while(iter.hasNext()){\n int pos = iter.next();\n int i = pos/51;\n int j = pos%51;\n grid[i][j] = 1;\n } \n }\n resetGrid(grid);\n return containVirus(grid);\n }\n \n public void resetGrid(int[][] grid){\n int rows = grid.length;\n int cols = grid[0].length;\n for(int i=0; i<rows; i++){\n for(int j=0; j<cols; j++){\n if(grid[i][j] > 0)\n grid[i][j] = 1;\n }\n }\n }\n \n public void buildWalls(Set<Integer> area, int[][] grid){\n Iterator<Integer> iter = area.iterator();\n while(iter.hasNext()){\n int next = iter.next();\n grid[next/51][next%51] = -1;\n }\n }\n \n public int dfs(int i, int j, int[][] grid, Set<Integer> threatenArea, Set<Integer> origArea){\n if(i < 0 || j < 0 || i == grid.length || j == grid[0].length || grid[i][j] == 2 || grid[i][j] == -1)\n return 0;\n if(grid[i][j] == 0){\n threatenArea.add(i*51 + j);\n return 1;\n }\n origArea.add(i*51+j);\n grid[i][j] = 2;\n int res = 0;\n res += dfs(i-1, j, grid, threatenArea, origArea);\n res += dfs(i+1, j, grid, threatenArea, origArea);\n res += dfs(i, j-1, grid, threatenArea, origArea);\n res += dfs(i, j+1, grid, threatenArea, origArea);\n return res;\n }\n} | 1 | 0 | [] | 0 |
contain-virus | Straight Forward Python Solution | straight-forward-python-solution-by-zlar-yofk | \nclass Solution:\n def containVirus(self, grid: List[List[int]]) -> int:\n\n rows, cols = len(grid), len(grid[0])\n\n def adj_cells(row, col): | zlareb1 | NORMAL | 2020-05-17T12:58:04.181767+00:00 | 2020-05-17T12:58:04.181817+00:00 | 905 | false | ```\nclass Solution:\n def containVirus(self, grid: List[List[int]]) -> int:\n\n rows, cols = len(grid), len(grid[0])\n\n def adj_cells(row, col):\n for r, c in [\n (row + 1, col),\n (row - 1, col),\n (row, col + 1),\n (row, col - 1),\n ]:\n if 0 <= r < rows and 0 <= c < cols:\n yield r, c\n\n def no_of_elements_in_2d_list(list_2d):\n return sum(len(li) for li in list_2d)\n\n def get_contaminated_areas():\n areas = []\n dangers = []\n walls = []\n seen = [[False] * cols for i in range(rows)]\n\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == 1 and not seen[r][c]:\n area = [(r, c)]\n danger = set()\n queue = [(r, c)]\n seen[r][c] = True\n wall = 0\n\n while queue:\n m, n = queue.pop(0)\n for i, j in adj_cells(m, n):\n index = (i, j)\n if grid[i][j] == 1 and not seen[i][j]:\n seen[i][j] = True\n queue.append(index)\n area.append(index)\n elif grid[i][j] == 0:\n wall += 1\n danger.add(index)\n areas.append(area)\n dangers.append(danger)\n walls.append(wall)\n\n return areas, dangers, walls\n\n def spread_virus(dangers):\n for danger in dangers:\n for row, col in danger:\n grid[row][col] = 1\n\n wall = 0\n areas, dangers, walls = get_contaminated_areas()\n\n while areas:\n area_count = len(areas)\n\n if no_of_elements_in_2d_list(areas) == rows * cols:\n return wall\n\n dangerest_index = 0\n\n for i in range(area_count):\n if len(dangers[i]) > len(dangers[dangerest_index]):\n dangerest_index = i\n\n wall += walls[dangerest_index]\n\n for i, j in areas[dangerest_index]:\n grid[i][j] = -1\n\n spread_virus(dangers[:dangerest_index] + dangers[dangerest_index + 1 :])\n\n areas, dangers, walls = get_contaminated_areas()\n\n return wall\n```\n | 1 | 0 | ['Breadth-First Search', 'Python3'] | 0 |
contain-virus | Accepted C# Solution with Union-Find | accepted-c-solution-with-union-find-by-m-jy2f | \n public class Solution\n {\n private static readonly (int di, int dj)[] _directions = { (0, 1), (0, -1), (1, 0), (-1, 0) };\n\n private cl | maxpushkarev | NORMAL | 2020-03-20T09:43:19.634134+00:00 | 2020-03-20T09:43:19.634168+00:00 | 281 | false | ```\n public class Solution\n {\n private static readonly (int di, int dj)[] _directions = { (0, 1), (0, -1), (1, 0), (-1, 0) };\n\n private class Unions\n {\n private readonly int[] _parents;\n private readonly int[] _ranks;\n\n public Unions(int n)\n {\n _parents = new int[n];\n _ranks = new int[n];\n for (int i = 0; i < n; i++)\n {\n _parents[i] = i;\n }\n }\n\n public int Find(int x)\n {\n if (x != _parents[x])\n {\n x = Find(_parents[x]);\n }\n return _parents[x];\n }\n\n public bool Union(int x, int y)\n {\n int px = Find(x);\n int py = Find(y);\n if (px == py)\n {\n return false;\n }\n if (_ranks[px] > _ranks[py])\n {\n _parents[py] = px;\n _ranks[px]++;\n }\n else\n {\n _parents[px] = py;\n _ranks[py]++;\n }\n return true;\n }\n }\n\n public int ContainVirus(int[][] grid)\n {\n int n = grid.Length;\n int m = grid[0].Length;\n\n int res = 0;\n while (true)\n {\n Unions dsu = new Unions(n * m);\n\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < m; j++)\n {\n int linear = i * m + j;\n\n if (grid[i][j] == 1)\n {\n foreach (var dir in _directions)\n {\n int newI = i + dir.di;\n int newJ = j + dir.dj;\n\n if (newI >= 0 && newI < n && newJ >= 0 && newJ < m && grid[newI][newJ] == 1)\n {\n dsu.Union(linear, newI * m + newJ);\n }\n }\n }\n }\n }\n\n IDictionary<int, ISet<int>> root2Cells = new Dictionary<int, ISet<int>>();\n\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < m; j++)\n {\n if (grid[i][j] == 1)\n {\n var root = dsu.Find(i * m + j);\n if (!root2Cells.ContainsKey(root))\n {\n root2Cells[root] = new HashSet<int>();\n }\n\n root2Cells[root].Add(i * m + j);\n }\n }\n }\n\n\n IList<(ISet<int> set, int root)> nextCellCollections =\n new List<(ISet<int> set, int root)>(root2Cells.Count);\n\n foreach (var r2c in root2Cells)\n {\n ISet<int> next = new HashSet<int>();\n\n foreach (var lidx in r2c.Value)\n {\n int i = lidx / m;\n int j = lidx % m;\n\n foreach (var dir in _directions)\n {\n int newI = i + dir.di;\n int newJ = j + dir.dj;\n\n if (newI >= 0 && newI < n && newJ >= 0 && newJ < m && (grid[newI][newJ] == 0 || grid[newI][newJ] == 2))\n {\n next.Add(newI * m + newJ);\n grid[newI][newJ] = 2;\n }\n }\n }\n\n nextCellCollections.Add((next, r2c.Key));\n }\n\n if (nextCellCollections.Count == 0)\n {\n break;\n }\n\n (ISet<int> set, int root)? max = null;\n foreach (var cand in nextCellCollections)\n {\n max = max ?? cand;\n if (cand.set.Count > max.Value.set.Count)\n {\n max = cand;\n }\n }\n\n\n foreach (var lidx in max.Value.set)\n {\n int i = lidx / m;\n int j = lidx % m;\n\n foreach (var dir in _directions)\n {\n int newI = i + dir.di;\n int newJ = j + dir.dj;\n\n if (newI >= 0 && newI < n && newJ >= 0 && newJ < m && grid[newI][newJ] == 1)\n {\n if (dsu.Find(newI * m + newJ) == max.Value.root)\n {\n res++;\n }\n }\n }\n }\n\n\n foreach (var lidx in root2Cells[max.Value.root])\n {\n int i = lidx / m;\n int j = lidx % m;\n grid[i][j] = 3;\n }\n\n\n nextCellCollections.Remove(max.Value);\n for (int collectionIdx = 0; collectionIdx < nextCellCollections.Count; collectionIdx++)\n {\n var cells = nextCellCollections[collectionIdx];\n\n foreach (var lidx in cells.set)\n {\n int i = lidx / m;\n int j = lidx % m;\n\n grid[i][j] = 1;\n }\n }\n \n if (nextCellCollections.Count == 0)\n {\n break;\n }\n }\n\n return res;\n }\n }\n``` | 1 | 0 | ['Union Find'] | 0 |
contain-virus | cell contained python bfs | cell-contained-python-bfs-by-je390-ln1q | 0: is a free cell\n1: is a contaminated cell that is spreading\n-1: is a contaminated cell that we stopped spreading\n\nfor each connected component of 1s\n1. a | je390 | NORMAL | 2020-01-07T02:35:18.621254+00:00 | 2020-01-07T02:35:18.621304+00:00 | 219 | false | 0: is a free cell\n1: is a contaminated cell that is spreading\n-1: is a contaminated cell that we stopped spreading\n\nfor each connected component of 1s\n1. a hashset of all the connected cells under this same connected component\n2. the number of walls it would take to quarantine this cc\n3. the number of cells it would contaminate if we let it spread one turn\n\npseudo code\n```\nareas = getallccs()\nwhile(areas):\n\tget the max area aka the one that stop the spread of the max number of cells\n\tarea = the max among all areas\n\ttotal += the number of walls for that area\n\tturn this area into -1 aka stop the propagation\n\tareas = getallccs() # recompute the areas\n```\n\nhow many walls given a cc?\n\ngiven a cell , look at its 4 neighbors, \nit one of them is a zero , it needs one wall\ndo that for all the cells\n\n\nhow many walls possible contaminations?\n\ngiven a cell , look at its 4 neighbors, \nit one of them is a zero , add it to a hashset\ndo that for all the cells\nand the length of that hashset if \nthe number of possible contamination\nhashset because a zero could be surrounded and counted multiple times\n\n\n\n\n\n```\nclass Solution(object):\n def containVirus(self, grid):\n total,areas = 0,self.f(grid)\n while(areas):\n areas.sort(key = lambda x: (x[2], -x[1]))\n total += areas[-1][1]\n self.quarantine(areas[-1][0],grid)\n areas.pop()\n self.spread(grid)\n areas = self.f(grid)\n return total\n \n def f(self,grid):\n areas = []\n gv = set([])\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1 and (i,j) not in gv: \n nw = 0\n q = collections.deque([(i,j)])\n vis = set([(i,j)])\n nb = set([])\n while(q):\n u = q.popleft()\n for v in [(u[0]+1,u[1]), (u[0]-1,u[1]), (u[0],u[1]+1), (u[0],u[1]-1)]:\n if 0<= v[0] < len(grid) and 0 <= v[1] < len(grid[0]) and v not in vis:\n if grid[v[0]][v[1]] == 1:\n q.append(v)\n gv.add(v)\n vis.add(v)\n elif grid[v[0]][v[1]] == 0:\n nb.add(v)\n nw +=1\n areas.append([vis,nw,len(nb)])\n return areas\n def quarantine(self,area,grid): for ei,ej in area: grid[ei][ej] = -1\n def spread(self,grid):\n ta = [(i,j) for i in range(len(grid)) for j in range(len(grid[0])) if grid[i][j] ==1]\n for u in ta:\n for v in [(u[0]+1,u[1]), (u[0]-1,u[1]), (u[0],u[1]+1), (u[0],u[1]-1)]:\n if 0<= v[0] < len(grid) and 0 <= v[1] < len(grid[0]) and grid[v[0]][v[1]] == 0: grid[v[0]][v[1]] = 1\n``` | 1 | 0 | [] | 1 |
contain-virus | [C++] 4ms DFS beats 100% | c-4ms-dfs-beats-100-by-whoisnoone-vg4s | \npublic:\n int containVirus(vector<vector<int>>& grid) {\n while (build_wall(grid)) {}\n return res;\n }\n \nprivate:\n int res = 0;\ | whoisnoone | NORMAL | 2019-10-15T04:28:26.991662+00:00 | 2019-10-15T04:39:43.577034+00:00 | 420 | false | ```\npublic:\n int containVirus(vector<vector<int>>& grid) {\n while (build_wall(grid)) {}\n return res;\n }\n \nprivate:\n int res = 0;\n int dfs(vector<vector<int>>& grid, int i, int j, int k, int& wall, vector<vector<int>>& infected_grid) {\n if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() || grid[i][j] < 0) return 0;\n if (grid[i][j] == k) {\n if (infected_grid[i][j] > 0) wall++; // only build wall on boundary\n return 0;\n }\n \n if (grid[i][j] == 1) {\n grid[i][j] = k; // grid[i][j] = 1 -> k, not boundary, don\'t build wall\n return dfs(grid, i + 1, j, k, wall, infected_grid) + dfs(grid, i, j + 1, k, wall, infected_grid)\n + dfs(grid, i - 1, j, k, wall, infected_grid) + dfs(grid, i, j - 1, k, wall, infected_grid);\n }\n \n grid[i][j] = k; // grid[i][j] = 0 -> k\n infected_grid[i][j]++; // record the boundary\n wall++; // only build wall on boundary\n return 1;\n }\n \n bool build_wall(vector<vector<int>>& grid) {\n int k = 1, m = grid.size(), n = grid[0].size(), max_infected = -1, K = 0, add_wall = 0;\n vector<vector<int>> infected_grid(m, vector<int>(n, 0));\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1) {\n int wall = 0, infected = dfs(grid, i, j, ++k, wall, infected_grid);\n if (max_infected < infected) {\n max_infected = infected;\n add_wall = wall;\n K = k;\n }\n }\n }\n }\n \n if (k == 1) return false; // no free infected area exists, stop\n \n res += add_wall;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] > 0) grid[i][j] = (grid[i][j] == K && infected_grid[i][j] <= 1) ? infected_grid[i][j] - 1 : 1; // set area inside new wall as -1, else where as 1\n }\n }\n return true;\n }\n``` | 1 | 0 | [] | 0 |
contain-virus | Simple Java DFS | simple-java-dfs-by-a_love_r-w8vn | ~~~java\n\nclass Solution {\n int m, n;\n int[] dx = new int[]{1,-1,0,0};\n int[] dy = new int[]{0,0,1,-1};\n \n boolean[][] visited;\n List> | a_love_r | NORMAL | 2019-07-23T02:28:31.272142+00:00 | 2019-07-23T02:28:31.272172+00:00 | 472 | false | ~~~java\n\nclass Solution {\n int m, n;\n int[] dx = new int[]{1,-1,0,0};\n int[] dy = new int[]{0,0,1,-1};\n \n boolean[][] visited;\n List<Set<Integer>> region;\n List<Set<Integer>> frontier;\n List<Integer> perimeter;\n \n public int containVirus(int[][] grid) {\n m = grid.length;\n n = grid[0].length;\n int ans = 0;\n \n while (true) {\n visited = new boolean[m][n];\n region = new ArrayList<>();\n frontier = new ArrayList<>();\n perimeter = new ArrayList<>();\n \n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1 && !visited[i][j]) {\n frontier.add(new HashSet<>());\n region.add(new HashSet<>());\n perimeter.add(0);\n dfs(grid, i, j);\n }\n }\n }\n \n if (region.size() == 0) return ans;\n \n int max = 0;\n for (int i = 1; i < frontier.size(); i++) {\n if (frontier.get(i).size() > frontier.get(max).size()) max = i;\n }\n ans += perimeter.get(max);\n \n for (int i = 0; i < region.size(); ++i) {\n if (i == max) {\n for (int code: region.get(i))\n grid[code / n][code % n] = -1;\n } else {\n for (int code: region.get(i)) {\n int r = code / n, c = code % n;\n for (int k = 0; k < 4; k++) {\n int nr = r + dx[k], nc = c + dy[k];\n if (nr >= 0 && nr < m && \n nc >= 0 && nc < n && \n grid[nr][nc] == 0)\n grid[nr][nc] = 1;\n }\n }\n }\n }\n }\n }\n \n private void dfs(int[][] grid, int x, int y) {\n int len = region.size();\n region.get(len-1).add(x * n + y);\n visited[x][y] = true;\n for (int k = 0; k < 4; k++) {\n int nx = x + dx[k], ny = y + dy[k];\n if (nx < 0 || ny < 0 || nx >= m || ny >= n) continue;\n if (grid[nx][ny] == 1 && !visited[nx][ny]) dfs(grid, nx, ny);\n else if (grid[nx][ny] == 0) {\n frontier.get(len-1).add(nx * n + ny);\n perimeter.set(len-1, perimeter.get(len-1)+1);\n }\n }\n }\n}\n\n~~~ | 1 | 0 | [] | 2 |
contain-virus | Simulation with Union-Find (C++, 12ms) | simulation-with-union-find-c-12ms-by-las-4z50 | This is a straight forward solution without any algorithmic tricks. I applied union-find here instead of DFS. Code is clear enough to understand. \nC++\nclass S | laseinefirenze | NORMAL | 2018-11-08T07:02:02.155605+00:00 | 2018-11-08T07:02:02.155647+00:00 | 403 | false | This is a straight forward solution without any algorithmic tricks. I applied union-find here instead of DFS. Code is clear enough to understand. \n```C++\nclass Solution {\n int M, N, K;\n vector<int> root, affect;\n \n // operations of Union-Find\n int find_root(int i) {\n if (root[i] == -1) return -1; // -1: this union cannot spread any more\n if (root[i] == i) return i;\n root[i] = find_root(root[i]);\n return root[i];\n }\n void union_set(int i, int j) {\n root[find_root(j)] = find_root(i);\n }\n \n void showGrid(vector<vector<int>>& grid) {\n for (int i=0; i<M; i++) {\n for (int j=0; j<N; j++) \n cout << grid[i][j] << \' \';\n cout << endl;\n }\n }\n \n void constructUnions(vector<vector<int>>& grid) {\n K = M * N;\n root.resize(K);\n affect.resize(K, 0);\n for (int i=0; i<K; i++) {\n int a = i / N, b = i % N;\n if (!grid[a][b]) \n root[i] = -1;\n else {\n root[i] = i;\n if (a && grid[a-1][b] && find_root(i) != find_root(i-N)) union_set(i-N, i);\n if (b && grid[a][b-1] && find_root(i) != find_root(i-1)) union_set(i-1, i);\n }\n }\n //showGrid(grid);\n }\n \n pair<int, int> findMostAffect(vector<vector<int>>& grid) {\n fill(affect.begin(), affect.end(), 0);\n for (int i=0; i<K; i++) {\n int a = i / N, b = i % N;\n if (grid[a][b]) continue;\n unordered_set<int> nei; // to avoid duplicate adding\n if (a>0 && grid[a-1][b] && find_root(i-N) != -1) nei.insert(root[i-N]);\n if (b>0 && grid[a][b-1] && find_root(i-1) != -1) nei.insert(root[i-1]);\n if (a<M-1 && grid[a+1][b] && find_root(i+N) != -1) nei.insert(root[i+N]);\n if (b<N-1 && grid[a][b+1] && find_root(i+1) != -1) nei.insert(root[i+1]);\n for (int n : nei) affect[n] ++;\n }\n int maxUnion = -1, mayAffect = 0, maxAffect = 0;\n for (int r=0; r<K; r++) {\n if (affect[r] > maxAffect) {\n maxAffect = affect[r];\n maxUnion = r;\n }\n mayAffect += affect[r];\n }\n //cout << "maxUnion:" << maxUnion << ", mayAffect:" << mayAffect << endl;\n return {maxUnion, mayAffect};\n }\n \n int buildWallAndGrow(vector<vector<int>>& grid, int maxUnion) {\n int walls = 0;\n \n // build walls\n for (int i=0; i<K; i++) {\n int a = i / N, b = i % N;\n if (grid[a][b] && find_root(i) == maxUnion) {\n if (a>0 && !grid[a-1][b]) walls ++;\n if (b>0 && !grid[a][b-1]) walls ++;\n if (a<M-1 && !grid[a+1][b]) walls ++;\n if (b<N-1 && !grid[a][b+1]) walls ++;\n }\n }\n \n // disable current union\n root[maxUnion] = -1;\n \n // growth of other unions\n vector<int> toAffect;\n for (int i=0; i<K; i++) {\n int a = i / N, b = i % N;\n if (!grid[a][b]) {\n if ((a>0 && grid[a-1][b] && find_root(i-N) != -1) ||\n (b>0 && grid[a][b-1] && find_root(i-1) != -1) ||\n (a<M-1 && grid[a+1][b] && find_root(i+N) != -1) ||\n (b<N-1 && grid[a][b+1] && find_root(i+1) != -1))\n {\n toAffect.push_back(i);\n }\n }\n }\n for (int i : toAffect) {\n int a = i / N, b = i % N;\n root[i] = i;\n grid[a][b] = 1;\n if (a>0 && grid[a-1][b] && find_root(i-N) != -1) union_set(i-N, i);\n if (b>0 && grid[a][b-1] && find_root(i-1) != -1) union_set(i-1, i);\n if (a<M-1 && grid[a+1][b] && find_root(i+N) != -1) union_set(i+N, i);\n if (b<N-1 && grid[a][b+1] && find_root(i+1) != -1) union_set(i+1, i);\n }\n \n //cout << "Walls:" << walls << endl;\n //showGrid(grid);\n return walls;\n }\n \npublic:\n \n int containVirus(vector<vector<int>>& grid) {\n if (!(M = grid.size()) || !(N = grid[0].size())) return 0;\n constructUnions(grid);\n \n int walls = 0;\n while (true) {\n auto p = findMostAffect(grid);\n int maxUnion = p.first;\n int mayAffect = p.second;\n \n if (mayAffect) \n walls += buildWallAndGrow(grid, maxUnion); \n else break;\n }\n \n return walls;\n }\n};\n``` | 1 | 0 | [] | 0 |
contain-virus | Java DFS beats 88% as of 10/21/18 | java-dfs-beats-88-as-of-102118-by-mach7-xwad | ``` class Solution { static int[] dir = {-1, 0, 1, 0, -1}; public int containVirus(int[][] grid) { if (grid == null || grid.length == 0 || grid[0].length == | mach7 | NORMAL | 2018-10-21T07:38:03.167515+00:00 | 2018-10-21T07:38:03.167577+00:00 | 468 | false | ```
class Solution {
static int[] dir = {-1, 0, 1, 0, -1};
public int containVirus(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
int m = grid.length, n = grid[0].length, target = 0, walls = 0;
for (int[] row: grid) {
for (int e: row) {
if (e == 1) target++;
}
}
while (target > 0) {
List<Set<Integer>> zeroList = new ArrayList<>();
List<List<int[]>> oneList = new ArrayList<>();
boolean[][] visited = new boolean[m][n];
for (int x = 0; x < m; x++) {
for (int y = 0; y < n; y++) {
if (grid[x][y] == 1 && !visited[x][y]) {
Set<Integer> zero = new HashSet<>();
List<int[]> one = new ArrayList<>();
nav(x, y, grid, visited, zero, one);
zeroList.add(zero);
oneList.add(one);
}
}
}
int index = -1, max = -1;
for (int i = 0; i < zeroList.size(); i++) {
Set<Integer> zeros = zeroList.get(i);
if (zeros.size() > max) {
max = zeros.size();
index = i;
}
}
List<int[]> ones = oneList.get(index);
for (int[] one: ones) {
grid[one[0]][one[1]] = -1;
for (int i = 0; i < 4; i++) {
int nx = one[0] + dir[i], ny = one[1] + dir[i + 1];
if (nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] == 0) {
walls++;
}
}
}
target -= ones.size();
Set<Integer> merged = new HashSet<>();
for (int i = 0; i < zeroList.size(); i++) {
if (i == index) continue;
merged.addAll(zeroList.get(i));
}
for (int z: merged) {
int x = z / n, y = z % n;
grid[x][y] = 1;
}
target += merged.size();
}
return walls;
}
private void nav(int x, int y, int[][] grid, boolean[][] visited, Set<Integer> zeros, List<int[]> ones) {
int m = grid.length, n = grid[0].length;
visited[x][y] = true;
ones.add(new int[] {x, y});
for (int i = 0; i < 4; i++) {
int nextX = x + dir[i], nextY = y + dir[i + 1];
if (nextX < 0 || nextX >= m ||
nextY < 0 || nextY >= n || visited[nextX][nextY]) continue;
if (grid[nextX][nextY] == 0) {
zeros.add(nextX * n + nextY);
} else if (grid[nextX][nextY] == 1) {
nav(nextX, nextY, grid, visited, zeros, ones);
}
}
}
}
```
| 1 | 0 | [] | 0 |
contain-virus | Java Union Find Solution. Simulate the evolution. | java-union-find-solution-simulate-the-ev-gx9e | Just provide another way to solve the problem. Although the code is lengthy, but the idea is simple and commented inline. \n\nclass Solution {\n public int c | crazy_y | NORMAL | 2018-01-10T09:19:28.328000+00:00 | 2018-01-10T09:19:28.328000+00:00 | 277 | false | Just provide another way to solve the problem. Although the code is lengthy, but the idea is simple and commented inline. \n```\nclass Solution {\n public int containVirus(int[][] grid) {\n int rst = 0;\n int s = solve(grid);\n while (s != 0) {\n rst += s;\n s = solve(grid);\n }\n return rst;\n }\n\n private int solve(int[][] g) {\n int r = g.length;\n int c = g[0].length;\n int[] uf = new int[getIdx(g, r - 1, c - 1) + 1];\n initUF(uf);\n int[][] dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n // First mark connected components into same group.\n for (int i = 0; i < r; ++i) {\n for (int j = 0; j < c; ++j) {\n if (g[i][j] <= 0) {\n continue;\n }\n for (int k = 0; k < 4; ++k) {\n int x = i + dir[k][0];\n int y = j + dir[k][1];\n if (x >= 0 && x < r && y >= 0 && y < c && g[x][y] > 0) {\n union(uf, getIdx(g, x, y), getIdx(g, i, j));\n }\n }\n }\n }\n // blankSets, key is group index, value set contains all adjacent 0s.\n Map<Integer, Set<Integer>> blankSets = new HashMap<>();\n // wallCounts, key is group index, value is count of walls to build.\n Map<Integer, Integer> wallCounts = new HashMap<>();\n // And then iterate graph, count adjacent 0s and walls to build.\n for (int i = 0; i < r; ++i) {\n for (int j = 0; j < c; ++j) {\n if (g[i][j] <= 0) {\n continue;\n }\n int idx = find(uf, getIdx(g, i, j));\n if (!blankSets.containsKey(idx)) {\n blankSets.put(idx, new HashSet<>());\n }\n for (int k = 0; k < 4; ++k) {\n int x = i + dir[k][0];\n int y = j + dir[k][1];\n if (x >= 0 && x < r && y >= 0 && y < c && g[x][y] == 0) {\n int blankIdx = getIdx(g, x, y);\n blankSets.get(idx).add(blankIdx);\n wallCounts.put(idx, wallCounts.getOrDefault(idx, 0) + 1);\n }\n }\n }\n }\n // And then find the connected component with max adjacent 0s.\n int maxIdx = 0;\n int maxSize = 0;\n int walls = 0;\n for (int idx : blankSets.keySet()) {\n Set<Integer> s = blankSets.get(idx);\n if (s.size() > maxSize) {\n maxSize = s.size();\n maxIdx = idx;\n walls = wallCounts.get(idx);\n }\n }\n if (maxSize == 0) {\n return 0;\n }\n // And finally, update the graph in-place, mark contained virus to be -1, \n // and spread other virus to adjacent 0s.\n int[][] tmp = cp(g);\n for (int i = 0; i < r; ++i) {\n for (int j = 0; j < c; ++j) {\n if (tmp[i][j] <= 0) {\n continue;\n }\n int idx = find(uf, getIdx(g, i, j));\n if (idx == maxIdx) {\n g[i][j] = -1;\n continue;\n }\n for (int k = 0; k < 4; ++k) {\n int x = i + dir[k][0];\n int y = j + dir[k][1];\n if (x >= 0 && x < r && y >= 0 && y < c && tmp[x][y] == 0) {\n g[x][y] = 1;\n }\n }\n }\n }\n return walls;\n }\n\n // 2d to 1d index mapping.\n private int getIdx(int[][] g, int x, int y) {\n return g[0].length * x + y;\n }\n\n // methods for union find set.\n private void initUF(int[] uf) {\n for (int i = 0; i < uf.length; ++i) {\n uf[i] = i;\n }\n }\n\n private int find(int[] uf, int a) {\n if (uf[a] == a) {\n return a;\n }\n int r = find(uf, uf[a]);\n uf[a] = r;\n return r;\n }\n\n private void union(int[] uf, int a, int b) {\n int ga = find(uf, a);\n int gb = find(uf, b);\n uf[gb] = ga;\n }\n\n private int[][] cp(int[][] g) {\n int[][] r = new int[g.length][g[0].length];\n for (int i = 0; i < g.length; ++i) {\n for (int j = 0; j < g[0].length; ++j) {\n r[i][j] = g[i][j];\n }\n }\n return r;\n }\n}\n``` | 1 | 0 | [] | 0 |
contain-virus | My ugly java DFS solution 19 ms with explaination | my-ugly-java-dfs-solution-19-ms-with-exp-aiab | The test case 3 is wrong. It should be 13 instead of 11.\nThe idea is to use dfs for each group of virus to find out how many cells will be infected and how man | jinsheng | NORMAL | 2017-12-17T04:13:37.845000+00:00 | 2017-12-17T04:13:37.845000+00:00 | 943 | false | The test case 3 is wrong. It should be 13 instead of 11.\nThe idea is to use dfs for each group of virus to find out how many cells will be infected and how many walls will be needed. If an adjacent good cells has been visited, next time it is reached by dfs, the count for walls still need to increase 1.\nThen we selected the group of virus with maximum number of new cells to be infected, and label/fix them. We keep this process until no new cells will be infected, which means either the spread is stopped or all the cells are infected.\n```\nclass Solution {\n int[][] dir = {{0,1},{0,-1},{-1,0},{1,0}};\n int m, n;\n public int containVirus(int[][] grid) {\n \tm = grid.length; n = grid[0].length;\n \tint res = 0;\n \twhile (true) {\n\t \tboolean [][] v = new boolean[m][n];\n\t \tint[] cur = new int[4];\t\t// cur[0] represents how many cell will be infected by this group tomorrow, cur[1] represents how many walls will be built if this group is chosen. cur[2] and cur[3] represents the start of the selected group \n\t \tfor (int i=0;i<m;i++) {\n\t \t\tfor (int j=0;j<n;j++) {\n\t \t\t\tif (grid[i][j]==1 && !v[i][j]) {\n\t \t\t\t\tboolean[][] z = new boolean[m][n];\t// z[i][j] represents if the cell is checked. if it's checked, cur[0] won't be counted, but cur[1] still need to increase 1;\n\t \t\t\t\tint[] rt = new int[2];\n\t \t\t\t\tdfs(grid,v,z,rt,i,j);\n\t \t\t\t\tif (rt[0]>cur[0]) {\n\t \t\t\t\t\tcur[0] = rt[0];\n\t \t\t\t\t\tcur[1] = rt[1];\n\t \t\t\t\t\tcur[2] = i;\n\t \t\t\t\t\tcur[3] = j;\n\t \t\t\t\t}\n\t \t\t\t}\n\t \t\t}\n\t \t}\n\t \tif (cur[0] == 0) {\n\t \t\treturn res;\n\t \t}\n\t \tres += cur[1];\n\t \tdfs1(grid, cur[2], cur[3]);\n\t \tfor (int i=0;i<m;i++) {\n\t \t\tfor (int j=0;j<n;j++) {\n\t \t\t\tif (grid[i][j]==0) {\n\t \t\t\t\tfor(int k=0;k<4;k++) {\n\t \t\t \t\tint x = i+dir[k][0], y = j+dir[k][1];\n\t \t\t \t\tif (x>=0 && x<m && y>=0 && y<n) {\n\t \t\t \t\t\tif (grid[x][y]==1) {\n\t \t\t \t\t\t\tgrid[i][j] = 3;\n\t \t\t \t\t\t\tbreak;\n\t \t\t \t\t\t}\n\t \t\t \t\t}\n\t \t\t\t\t}\n\t \t\t\t}\n\t \t\t}\n \t\t}\n\t \tfor (int i=0;i<m;i++) {\n\t \t\tfor (int j=0;j<n;j++) {\n\t \t\t\tif (grid[i][j]==3) {\n\t \t\t\t\tgrid[i][j]=1;\n\t \t\t\t}\n\t \t\t}\n \t\t}\n \t}\n }\n void dfs1(int[][]grid, int i, int j) {\t\t// change the selected cells from 1 to 2. these cells will be fixed and we won't touch them anymore. \n \tgrid[i][j] = 2;\n \tfor(int k=0;k<4;k++) {\n \t\tint x = i+dir[k][0], y = j+dir[k][1];\n \t\tif (x>=0 && x<m && y>=0 && y<n) {\n \t\t\tif (grid[x][y]==1) {\n \t\t\t\tdfs1(grid,x,y);\n \t\t\t}\n \t\t}\n \t}\n }\n void dfs(int[][]grid, boolean[][]v, boolean[][] z, int[] rt,int i, int j) {\n \tint[] res = new int[2];\n \tv[i][j] = true;\n \tfor(int k=0;k<4;k++) {\n \t\tint x = i+dir[k][0], y = j+dir[k][1];\n \t\tif (x>=0 && x<m && y>=0 && y<n) {\n \t\t\tif (grid[x][y]==0) {\n \t\t\t\trt[1]++;\n \t\t\t\tif (!z[x][y]) {\n \t\t\t\t\tz[x][y] = true;\n \t\t\t\t\trt[0]++;\n \t\t\t\t}\n \t\t\t}\n \t\t\tif (grid[x][y]==1 && !v[x][y]) {\n \t\t\t\tdfs(grid,v,z,rt,x,y);\n \t\t\t}\n \t\t}\n \t}\n }\n}\n``` | 1 | 0 | [] | 0 |
contain-virus | [749. Contain Virus] C++_AC_16ms_DFS | 749-contain-virus-c_ac_16ms_dfs-by-jason-8zbx | Pretty straightforward problem, by using DFS and following the requirements of this problem.\n\n class Solution {\n public:\n int containVirus(vector>& | jasonshieh | NORMAL | 2017-12-17T20:44:54.753000+00:00 | 2017-12-17T20:44:54.753000+00:00 | 449 | false | Pretty straightforward problem, by using DFS and following the requirements of this problem.\n\n class Solution {\n public:\n int containVirus(vector<vector<int>>& grid) {\n if(grid.empty()) return 0;\n int m = grid.size();\n int n = grid[0].size();\n int res = 0;\n //The number of rows and columns of grid will each be in the range [1, 50]. i*100 + j as the "index number"\n while(true){\n vector<vector<bool>> check(m, vector<bool>(n, false));\n //for dfs, find the continuous region\n\n unordered_map<int, unordered_set<int>> cells;\n // the cells(value = 0) will be affected by the region\n\n unordered_map<int, int> length;\n //the length of each region\n \n int max_region_id = 0;\n int max_region_length = 0;\n int max_region_cells = 0;\n for(int i = 0; i < m; ++i){\n for(int j = 0; j < n; ++j){\n if(grid[i][j] == 1 && !check[i][j]) {//go into the region search\n int id = i * 100 + j;\n find_bound(grid, length, check, i, j, m, n, cells, id);\n if(length[id]){\n if(cells[id].size() > max_region_cells){\n //if the current region is much more serious\n max_region_cells = cells[id].size();\n max_region_length = length[id];\n max_region_id = id;\n }\n }\n }\n }\n }\n if(max_region_length == 0) break;\n res += max_region_length;\n set_wall(grid, max_region_id/100, max_region_id%100, m, n);\n cells.erase(max_region_id);\n for(auto v : cells){\n update(grid, v.second, m, n);\n }\n }\n return res;\n \n }\n void set_wall(vector<vector<int>>& grid, int i, int j, int m, int n){\n grid[i][j] = -1;\n if(i-1 >= 0 && grid[i-1][j] == 1) set_wall(grid, i-1, j, m, n);\n if(i+1 < m && grid[i+1][j] == 1) set_wall(grid, i+1, j, m, n);\n if(j-1 >= 0 && grid[i][j-1] == 1) set_wall(grid, i, j-1, m, n);\n if(j+1 < n && grid[i][j+1] == 1) set_wall(grid, i, j+1, m, n);\n }\n \n void find_bound(vector<vector<int>>& grid, unordered_map<int, int>& length, vector<vector<bool>>& check, int i, int j, int m, int n, unordered_map<int, unordered_set<int>>& cells, int id){\n check[i][j] = true;\n if(i-1 >= 0 && grid[i-1][j] == 0) {length[id]++; cells[id].insert((i-1)*100 + j);}\n if(j-1 >= 0 && grid[i][j-1] == 0) {length[id]++; cells[id].insert(i*100 + j-1);}\n if(i+1 < m && grid[i+1][j] == 0) {length[id]++; cells[id].insert((i+1)*100 + j);}\n if(j+1 < n && grid[i][j+1] == 0) {length[id]++; cells[id].insert(i*100 + j + 1);}\n if(i-1 >= 0 && grid[i-1][j] == 1 && !check[i-1][j]) find_bound(grid, length, check, i-1, j, m, n, cells, id);\n if(j-1 >= 0 && grid[i][j-1] == 1 && !check[i][j-1]) find_bound(grid, length, check, i, j-1, m, n, cells, id);\n if(i+1 < m && grid[i+1][j] == 1 && !check[i+1][j]) find_bound(grid, length, check, i+1, j, m, n, cells, id);\n if(j+1 < n && grid[i][j+1] == 1 && !check[i][j+1]) find_bound(grid, length, check, i, j+1, m, n, cells, id);\n }\n \n void update(vector<vector<int>>& grid, unordered_set<int>& bound, int m, int n){\n for(auto idx : bound){\n int i = idx/100;\n int j = idx%100;\n grid[i][j] = 1;\n }\n }\n }; | 1 | 0 | [] | 0 |
contain-virus | Naive C++ solution using BFS | naive-c-solution-using-bfs-by-frank_fan-xmaz | Just follow the instruction of the problem. You can run it to see the output of every stage. Hope to find a more elegant algorithm.\n\nclass Solution {\npublic: | frank_fan | NORMAL | 2017-12-17T04:04:22.581000+00:00 | 2017-12-17T04:04:22.581000+00:00 | 927 | false | Just follow the instruction of the problem. You can run it to see the output of every stage. Hope to find a more elegant algorithm.\n```\nclass Solution {\npublic:\n int containVirus(vector<vector<int>>& grid) {\n size_t row = grid.size(), col = grid[0].size();\n int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n \n vector<vector<bool>> control = vector<vector<bool>>(row, vector<bool>(col, false));\n int numWalls = 0;\n while (true) {\n vector<vector<bool>> visited = vector<vector<bool>>(row, vector<bool>(col, false));\n vector<vector<int>> infection = vector<vector<int>>(row, vector<int>(col, 0));\n int mostInfection = 0;\n for (int x = 0; x < row; x++) {\n for (int y = 0; y < col; y++) {\n if (!control[x][y] && !visited[x][y] && grid[x][y] == 1) {\n vector<vector<bool>> infectionVisited = vector<vector<bool>>(row, vector<bool>(col, false));\n visited[x][y] = true;\n int infectionSize = 0;\n queue<pair<int, int>> bfs;\n bfs.push({x, y});\n while (!bfs.empty()) {\n auto point = bfs.front();\n int px = point.first, py = point.second;\n bfs.pop();\n \n for (size_t i = 0; i < 4; i++) {\n int newx = px + dirs[i][0], newy = py + dirs[i][1];\n if (newx >= 0 && newx < row && newy >= 0 && newy < col) {\n if (!control[newx][newy] && !visited[newx][newy]) {\n if (grid[newx][newy] == 1) {\n visited[newx][newy] = true;\n bfs.push({newx, newy});\n } else if (!infectionVisited[newx][newy]){\n infectionVisited[newx][newy] = true;\n infectionSize ++;\n }\n }\n }\n }\n }\n cout << "(" << x << ", " << y << ") infects: " << infectionSize << endl;\n infection[x][y] = infectionSize;\n mostInfection = max(mostInfection, infectionSize);\n }\n }\n }\n \n if (mostInfection == 0) {\n break;\n }\n \n for (int x = 0; x < row; x++) {\n bool complete = false;\n for (int y = 0; y < col; y++) {\n if (infection[x][y] == mostInfection) {\n visited = vector<vector<bool>>(row, vector<bool>(col, false));\n visited[x][y] = true;\n queue<pair<int, int>> bfs;\n bfs.push({x, y});\n while (!bfs.empty()) {\n auto point = bfs.front();\n int px = point.first, py = point.second;\n bfs.pop();\n \n control[x][y] = true;\n for (size_t i = 0; i < 4; i++) {\n int newx = px + dirs[i][0], newy = py + dirs[i][1];\n if (newx >= 0 && newx < row && newy >= 0 && newy < col) {\n if (!control[newx][newy] && !visited[newx][newy]) {\n if (grid[newx][newy] == 1) {\n control[newx][newy] = true;\n visited[newx][newy] = true;\n bfs.push({newx, newy});\n } else {\n numWalls ++;\n }\n }\n }\n }\n }\n infection[x][y] = 0;\n complete = true;\n break;\n }\n }\n if (complete) {\n break;\n }\n }\n cout << "Walls: " << numWalls << endl;\n \n vector<vector<int>> newGrid = grid;\n for (int x = 0; x < row; x++) {\n for (int y = 0; y < col; y++) {\n if (infection[x][y] > 0) {\n visited = vector<vector<bool>>(row, vector<bool>(col, false));\n visited[x][y] = true;\n queue<pair<int, int>> bfs;\n bfs.push({x, y});\n while (!bfs.empty()) {\n auto point = bfs.front();\n int px = point.first, py = point.second;\n bfs.pop();\n \n for (size_t i = 0; i < 4; i++) {\n int newx = px + dirs[i][0], newy = py + dirs[i][1];\n if (newx >= 0 && newx < row && newy >= 0 && newy < col) {\n if (!control[newx][newy] && !visited[newx][newy]) {\n if (grid[newx][newy] == 1) {\n visited[newx][newy] = true;\n bfs.push({newx, newy});\n } else {\n newGrid[newx][newy] = 1;\n }\n }\n }\n }\n }\n }\n }\n }\n grid = newGrid;\n for (auto line : newGrid) {\n for (auto item : line) {\n cout << item << ' ';\n }\n cout << endl;\n }\n cout << "===" << endl;\n }\n return numWalls;\n }\n};\n``` | 1 | 0 | [] | 4 |
contain-virus | Explained solution 4ms | explained-solution-7ms-by-aviadblumen-wzlx | Code | aviadblumen | NORMAL | 2025-03-27T13:13:34.603237+00:00 | 2025-03-27T13:14:37.794385+00:00 | 6 | false | 
# Code
```cpp []
class Solution {
int m,n;
public:
void spread_to_neighbors(vector<vector<int>>& board, int r, int c,int prev_marker, int marker){
// skip out of border and blocked cells
if (r < 0 || c < 0 || r>=m || c >=n || board[r][c] == INT_MAX )
return;
bool is_infected = board[r][c] == prev_marker;
board[r][c] = marker;
if (is_infected){
spread_to_neighbors(board,r,c+1,prev_marker,marker);
spread_to_neighbors(board,r,c-1,prev_marker,marker);
spread_to_neighbors(board,r+1,c,prev_marker,marker);
spread_to_neighbors(board,r-1,c,prev_marker,marker);
}
}
void fill_area(vector<vector<int>>& board, int r, int c,int marker, int& walls, int& num_adj){
// skip out of border, visited, and blocked cells
if (r < 0 || c < 0 || r>=m || c >=n || board[r][c] == marker || board[r][c] == INT_MAX )
return;
// empty neighbor cell
if (board[r][c] <= 0){
walls++;
// add adjacent empty cell if visited the first time
if (board[r][c] != -marker)
num_adj++;
board[r][c] = -marker;
return;
}
board[r][c] = marker;
fill_area(board,r,c+1,marker,walls,num_adj);
fill_area(board,r,c-1,marker,walls,num_adj);
fill_area(board,r+1,c,marker,walls,num_adj);
fill_area(board,r-1,c,marker,walls,num_adj);
}
int containVirus(vector<vector<int>>& board) {
int total_walls = 0;
m = size(board), n = size(board[0]);
unordered_map<int, pair<int,int>> infected_areas,prev_infected;
// used for infected areas marking
int marker = 2;
int walls, num_adj;
// at the beginning all cells are need to be checked if infected
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
prev_infected[n*i+j] = {i,j};
}
}
while(true){
// [num_adj, num_walls, x, y]
vector<int> area_for_del({0,0,0,0});
for(auto [_, pos] : prev_infected){
auto [i,j] = pos;
int v = board[i][j];
// marking each infected area by a different positive integer
if (v > 0 && infected_areas.count(v)==0){
walls = 0;
num_adj = 0;
fill_area(board,i,j,marker,walls,num_adj);
infected_areas[marker] = {i,j};
if (num_adj > area_for_del[0])
area_for_del = {num_adj, walls, i ,j};
marker++;
}
}
// stop if all area is infected or quarantined
if (area_for_del[0] == 0) break;
// block infected area with most neighbors
total_walls += area_for_del[1];
fill_area(board,area_for_del[2],area_for_del[3],INT_MAX,walls,num_adj);
// spread to neighbors
for (auto& [used_marker, pos] :infected_areas){
spread_to_neighbors(board, pos.first, pos.second, used_marker, marker);
marker++;
}
swap(prev_infected, infected_areas);
infected_areas.clear();
}
return total_walls;
}
};
``` | 0 | 0 | ['C++'] | 0 |
contain-virus | C++ | Simple DFS Solution | c-simple-dfs-solution-by-kena7-0fwv | Code | kenA7 | NORMAL | 2025-03-18T14:16:58.393645+00:00 | 2025-03-18T14:16:58.393645+00:00 | 8 | false |
# Code
```cpp []
class Solution {
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};
int m,n;
bool isValidMove(int x, int y) {
return x>=0 && y>=0 && x<m && y<n;
}
void dfs(int i,int j, vector<vector<int>>& g, set<pair<int,int>> &st)
{
g[i][j]=-1; // Mark as visited
//Move to next infected
for(int k=0;k<4;k++)
{
int x=i+dx[k], y=j+dy[k];
if(isValidMove(x,y)) {
if(g[x][y]==1)
dfs(x,y,g,st);
else if(g[x][y]==0)
st.insert({x,y});
}
}
}
int constructWalls(int i,int j, vector<vector<int>>& g)
{
g[i][j]=-2; // Marked as sealed within walls
int wallsCount=0;
for(int k=0;k<4;k++)
{
int x=i+dx[k], y=j+dy[k];
if(isValidMove(x,y)) {
if(g[x][y]==0)
wallsCount++;
else if(g[x][y]==-1)
wallsCount+= constructWalls(x,y,g);
}
}
return wallsCount;
}
void spreadToNearest(int i,int j, vector<vector<int>>& g)
{
g[i][j]=1; // Marked as infected
for(int k=0;k<4;k++)
{
int x=i+dx[k], y=j+dy[k];
if(isValidMove(x,y)) {
if(g[x][y]==0)
g[x][y]=1;
else if(g[x][y]==-1)
spreadToNearest(x,y,g);
}
}
}
public:
int containVirus(vector<vector<int>>& g)
{
m=g.size(),n=g[0].size();
int totalWalls=0;
while(true)
{
//Find component that threatens the most uninfected cells
int maxInfected=0,x=0,y=0;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(g[i][j]==1)
{
set<pair<int,int>>st;
dfs(i,j,g, st);
int currInfected=st.size();
if(currInfected>maxInfected)
{
maxInfected=currInfected;
x=i,y=j;
}
}
}
}
if(maxInfected==0)
break;
int wallsRequired=constructWalls(x,y,g);
totalWalls+=wallsRequired;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(g[i][j]==-1)
{
spreadToNearest(i,j,g);
}
}
}
}
return totalWalls;
}
};
``` | 0 | 0 | ['C++'] | 0 |
contain-virus | Ultra-Fast Virus Containment Algorithm - Optimized DFS with 1D indexing | ultra-fast-virus-containment-algorithm-o-cdnk | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Baltazin | NORMAL | 2025-03-14T12:11:17.901596+00:00 | 2025-03-14T12:11:17.901596+00:00 | 5 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```csharp []
public class Solution {
private static readonly int[][] directions = { new[] { 0, 1 }, new[] { 1, 0 }, new[] { 0, -1 }, new[] { -1, 0 } };
public int ContainVirus(int[][] isInfected) {
int m = isInfected.Length, n = isInfected[0].Length, totalWalls = 0;
while (true) {
List<HashSet<int>> regions = new();
List<HashSet<int>> threats = new();
List<int> wallsNeeded = new();
bool[] visited = new bool[m * n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (isInfected[i][j] == 1 && !visited[i * n + j]) {
HashSet<int> region = new(), threat = new();
int walls = 0;
DFS(isInfected, visited, i, j, n, region, threat, ref walls);
regions.Add(region);
threats.Add(threat);
wallsNeeded.Add(walls);
}
}
}
if (regions.Count == 0) break;
int maxThreatIndex = 0;
for (int i = 1; i < threats.Count; i++) {
if (threats[i].Count > threats[maxThreatIndex].Count)
maxThreatIndex = i;
}
totalWalls += wallsNeeded[maxThreatIndex];
foreach (int cell in regions[maxThreatIndex])
isInfected[cell / n][cell % n] = -1;
for (int i = 0; i < regions.Count; i++) {
if (i != maxThreatIndex)
foreach (int cell in threats[i])
isInfected[cell / n][cell % n] = 1;
}
}
return totalWalls;
}
private void DFS(int[][] isInfected, bool[] visited, int i, int j, int n, HashSet<int> region, HashSet<int> threat, ref int walls) {
int m = isInfected.Length;
Stack<int> stack = new();
stack.Push(i * n + j);
while (stack.Count > 0) {
int cell = stack.Pop();
i = cell / n;
j = cell % n;
if (visited[cell]) continue;
visited[cell] = true;
region.Add(cell);
foreach (var dir in directions) {
int ni = i + dir[0], nj = j + dir[1], nextCell = ni * n + nj;
if (ni >= 0 && ni < m && nj >= 0 && nj < n) {
if (isInfected[ni][nj] == 0) {
threat.Add(nextCell);
walls++;
} else if (isInfected[ni][nj] == 1 && !visited[nextCell]) {
stack.Push(nextCell);
}
}
}
}
}
}
``` | 0 | 0 | ['C#'] | 0 |
contain-virus | Lengthy But Simple Java Solution | lengthy-but-simple-java-solution-by-deco-9rub | IntuitionThe solution is simple. We need to keep doing dfs/bfs until and unless all the infection is spread or blocked.ApproachKeep track of infected nodes and | decodificar_e | NORMAL | 2025-02-05T20:14:16.134051+00:00 | 2025-02-05T20:14:16.134051+00:00 | 8 | false | # Intuition
The solution is simple. We need to keep doing dfs/bfs until and unless all the infection is spread or blocked.
# Approach
Keep track of infected nodes and non infected nodes through bfs/dfs at each step. This will let us know which island of nodes to close such infection is minimal.
# Complexity
- Time complexity:
O((m×n)×(m×n+m×nlog(m×n)))
- Space complexity:
O(m×n)
# Code
```java []
class Data {
int len; // number of non infected
List<int []> non; // list of cordinates of non infected
List<int []> inf; // list of cordinates of infected
int gates; // gates required to block the spread
Data(int len, int gates, List<int []> non, List<int []> inf) {
this.len = len;
this.non = non;
this.inf = inf;
this.gates = gates;
}
}
class Solution {
int x[] = {1, 0, -1, 0};
int y[] = {0, 1, 0, -1};
boolean vis[][];
Data bfs(int mat[][], int sx, int sy) {
Queue<int[]> qu = new LinkedList<>();
int n = mat[0].length;
int m = mat.length;
int cnt = 0;
int gates = 0;
qu.add(new int[]{sx, sy});
vis[sx][sy] = true;
List<int []> non = new ArrayList<>();
List<int []> inf = new ArrayList<>();
boolean visnI[][] = new boolean[50][50];
inf.add(new int[]{sx, sy});
while(!qu.isEmpty()) {
int []temp = qu.poll();
int a = temp[0];
int b = temp[1];
for(int i=0;i<4;i++) {
int p = a + x[i];
int q = b + y[i];
if(p >=0 && q >= 0 && p < m && q < n) {
if(mat[p][q] == 0) {
non.add(new int[]{p ,q});
if(visnI[p][q] == false) { // count distinct number of non infected which can be spread
cnt++;
visnI[p][q] =true;
}
gates++; // gates required to close the infection, it can come from any infected node
} else if(mat[p][q] == 1 && vis[p][q] == false) {
qu.add(new int[]{p,q});
inf.add(new int[]{p,q});
vis[p][q] = true;
}
}
}
}
return new Data(cnt, gates, non, inf);
}
public int containVirus(int[][] mat) {
int m = mat.length;
int n = mat[0].length;
int ans= 0;
while(true) {
vis = new boolean[m][n];
PriorityQueue<Data> pq = new PriorityQueue<>((a, b) -> {
return b.len - a.len;
});
for(int i=0;i<m;i++) {
for(int j=0;j<n;j++) {
if(mat[i][j] == 1 && vis[i][j] == false) {
Data res = bfs(mat, i, j);
pq.add(res);
}
}
}
if(pq.isEmpty())
break;
Data temp = pq.poll();
ans+=temp.gates;
for(int []d: temp.inf) {
mat[d[0]][d[1]] = -1; // Mark -1 to block the infection such that it does not gets picked up in the bfs
}
while(!pq.isEmpty()) {
Data rex = pq.poll();
for(int []t: rex.non)
mat[t[0]][t[1]] = 1; // Mark 1 to spread the infection where gate is not closed
}
return ans;
}
}
``` | 0 | 0 | ['Java'] | 0 |
contain-virus | C++ Easy Solution | c-easy-solution-by-harishnandre-tnhn | Code | harishnandre | NORMAL | 2025-01-30T19:47:18.826590+00:00 | 2025-01-30T19:47:18.826590+00:00 | 25 | false |
# Code
```cpp []
class Solution {
public:
vector<int> del = {-1, 0, 1, 0};
void dfs(int i, int j, vector<vector<int>>& isInfected, vector<vector<int>>& vis, vector<int>& eachComp, int n, int m) {
vis[i][j] = 1;
int node = i * m + j;
eachComp.push_back(node);
for (int k = 0; k < 4; k++) {
int r = i + del[k];
int c = j + del[(k + 1) % 4];
if (r >= 0 && c >= 0 && r < n && c < m && isInfected[r][c] == 1 && !vis[r][c]) {
dfs(r, c, isInfected, vis, eachComp, n, m);
}
}
}
int getCountOfNeigh(vector<int>& component, int n, int m, vector<vector<int>>& isInfected) {
int count = 0;
set<pair<int, int>> uniqueNeigh;
for (int node : component) {
int r = node / m;
int c = node % m;
for (int k = 0; k < 4; k++) {
int nr = r + del[k];
int nc = c + del[(k + 1) % 4];
if (nr >= 0 && nc >= 0 && nr < n && nc < m && isInfected[nr][nc] == 0) {
uniqueNeigh.insert({nr, nc});
}
}
}
return uniqueNeigh.size();
}
void increaseTheDecease(vector<int>& component, int n, int m, vector<vector<int>>& isInfected) {
vector<int> newComp = component;
for (int node : component) {
int r = node / m;
int c = node % m;
for (int k = 0; k < 4; k++) {
int nr = r + del[k];
int nc = c + del[(k + 1) % 4];
if (nr >= 0 && nc >= 0 && nr < n && nc < m && isInfected[nr][nc] == 0) {
isInfected[nr][nc] = 1;
newComp.push_back(nr * m + nc);
}
}
}
component = newComp;
}
int getCountOfWalls(vector<int>& component, int n, int m, vector<vector<int>>& isInfected) {
int walls = 0;
for (int node : component) {
int r = node / m;
int c = node % m;
for (int k = 0; k < 4; k++) {
int nr = r + del[k];
int nc = c + del[(k + 1) % 4];
if (nr >= 0 && nc >= 0 && nr < n && nc < m && isInfected[nr][nc] == 0) {
walls++;
}
}
}
return walls;
}
int containVirus(vector<vector<int>>& isInfected) {
int n = isInfected.size(), m = isInfected[0].size();
int totalWalls = 0;
while (true) {
vector<vector<int>> components;
vector<vector<int>> vis(n, vector<int>(m, 0));
// Find all infected components
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (!vis[i][j] && isInfected[i][j] == 1) {
vector<int> eachComp;
dfs(i, j, isInfected, vis, eachComp, n, m);
components.push_back(eachComp);
}
}
}
if (components.empty()) break;
// Choose the component with the maximum number of neighbors
int maxNeigh = -1, chosenIdx = -1;
for (int i = 0; i < components.size(); i++) {
int count = getCountOfNeigh(components[i], n, m, isInfected);
if (count > maxNeigh) {
maxNeigh = count;
chosenIdx = i;
}
}
if (maxNeigh == 0) break; // No spread possible
// Contain the most dangerous region
totalWalls += getCountOfWalls(components[chosenIdx], n, m, isInfected);
for (int node : components[chosenIdx]) {
int r = node / m, c = node % m;
isInfected[r][c] = -1; // Mark as contained
}
// Spread the remaining components
for (int i = 0; i < components.size(); i++) {
if (i != chosenIdx) {
increaseTheDecease(components[i], n, m, isInfected);
}
}
}
return totalWalls;
}
};
``` | 0 | 0 | ['Depth-First Search', 'Matrix', 'C++'] | 0 |
contain-virus | 749. Contain Virus | 749-contain-virus-by-g8xd0qpqty-6d1b | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | G8xd0QPqTy | NORMAL | 2024-12-29T08:10:13.264770+00:00 | 2024-12-29T08:10:13.264770+00:00 | 15 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
import java.util.*;
class Cell {
int row, col;
Cell(int row, int col) {
this.row = row;
this.col = col;
}
}
class InfectionCluster {
int wallsNeeded, exposedCells;
List<Cell> infectedCells;
InfectionCluster() {
this.wallsNeeded = 0;
this.exposedCells = 0;
this.infectedCells = new ArrayList<>();
}
}
class Solution {
private static final int[] DR = {-1, 1, 0, 0};
private static final int[] DC = {0, 0, -1, 1};
private boolean isValid(int x, int y, int rows, int cols) {
return x >= 0 && x < rows && y >= 0 && y < cols;
}
private void exploreCluster(int x, int y, int rows, int cols, int[][] grid, boolean[][] visited, boolean[][] unvisitedCells, InfectionCluster cluster) {
visited[x][y] = true;
cluster.infectedCells.add(new Cell(x, y));
for (int i = 0; i < 4; i++) {
int nx = x + DR[i], ny = y + DC[i];
if (isValid(nx, ny, rows, cols) && !visited[nx][ny] && grid[nx][ny] != -999) {
if (grid[nx][ny] == 1) {
exploreCluster(nx, ny, rows, cols, grid, visited, unvisitedCells, cluster);
} else if (grid[nx][ny] == 0) {
cluster.wallsNeeded++;
if (!unvisitedCells[nx][ny]) {
unvisitedCells[nx][ny] = true;
cluster.exposedCells++;
}
}
}
}
}
public int containVirus(int[][] grid) {
int totalWalls = 0;
int rows = grid.length;
int cols = grid[0].length;
while (true) {
PriorityQueue<InfectionCluster> maxHeap = new PriorityQueue<>((a, b) -> Integer.compare(b.exposedCells, a.exposedCells));
boolean[][] visited = new boolean[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == 1 && !visited[i][j]) {
InfectionCluster cluster = new InfectionCluster();
exploreCluster(i, j, rows, cols, grid, visited, new boolean[rows][cols], cluster);
if (cluster.exposedCells > 0) {
maxHeap.add(cluster);
}
}
}
}
if (maxHeap.isEmpty()) {
break;
}
InfectionCluster largestCluster = maxHeap.poll();
totalWalls += largestCluster.wallsNeeded;
for (Cell infectedCell : largestCluster.infectedCells) {
grid[infectedCell.row][infectedCell.col] = -999;
}
while (!maxHeap.isEmpty()) {
InfectionCluster cluster = maxHeap.poll();
for (Cell infectedCell : cluster.infectedCells) {
for (int i = 0; i < 4; i++) {
int nx = infectedCell.row + DR[i], ny = infectedCell.col + DC[i];
if (isValid(nx, ny, rows, cols) && grid[nx][ny] == 0) {
grid[nx][ny] = 1;
}
}
}
}
}
return totalWalls;
}
}
``` | 0 | 0 | ['Java'] | 0 |
contain-virus | JavaScript | Simple Solution Written for Clarity | javascript-simple-solution-written-for-c-i4pi | null | Faheem-maker | NORMAL | 2024-12-12T03:40:34.626044+00:00 | 2024-12-12T03:40:34.626044+00:00 | 6 | false | # Intuition\nIn order to solve the problem, we are going to simulate the exact process. In code, the idea\'s as simple as writing this loop:\n```javascript\nvar result = 0;\n\nlet tmp = 0;\n\ndo {\n tmp = contain(isInfected);\n result += tmp;\n spread(isInfected);\n} while (tmp != 0);\n\nreturn result;\n```\nThis loop simulates a day-to-day process. Each day, we contain the most dangrous region, then we spread the remaining regions\n\n# Approach\nLet\'s first understand the methods being used:\n- `contain(board)`: Finds the most dangrous region on the board and secures it by replacing each cell with `2`, indicating that the cell is fenced. Returns the number of walls used to secure the area.\n - `countCells(board, i, j)`: Finds the number of healthy cells that would be infected by the given region if we do nothing about it. It uses DFS to find the number of cells that would be infected by given coordinates.\n - `countWalls(board, i, j)`: Similar to `countCells`, but it finds the number of walls required to secure an area.\n - `secure(board, i, j)`: Secure the given region by replacing each infected cell with `2`.\n- `spread(board)`: Spreads each unfenced region on the board towards its neighbors.\nWe can now use these functions to solve the problem. We are going to use `contain` on each iterations to contain the most dangrous region and find the number of walls used. If there are no regions to secure, the game is over and we return the number of walls used so far, otherwise, we spread the remaining regions.\n\n```javascript\nvar result = 0; // Total number of walls used\n\nlet tmp = 0; // Counter variable keeping track of current number of walls\n\ndo {\n tmp = contain(isInfected); // Find the number of walls used\n result += tmp;\n spread(isInfected); // Spreads the board if there are any uncontained regions\n} while (tmp != 0);\n\nreturn result; // If no walls were used in the last iteration, the game is over and we return the total number of walls\n```\n\nThe remaining functions simply use DFS and follows a similar pattern. In fact, I could have written a single DFS function to compute all of this, but I wanted to make the solution more clearer.\n\n# Code\n```javascript []\n/**\n * @param {number[][]} isInfected\n * @return {number}\n */\nvar containVirus = function(isInfected) {\n // Find the most dangrous region\n var result = 0;\n\n let tmp = 0;\n\n do {\n tmp = contain(isInfected);\n result += tmp;\n spread(isInfected);\n } while (tmp != 0);\n\n return result;\n};\n\nfunction contain(board) {\n let max = 0;\n let x = -1;\n let y = -1;\n\n var visited = {};\n\n for (let i = 0; i < board.length; i++) {\n for (let j = 0; j < board[i].length; j++) {\n if (board[i][j] == 1 && !visited[i + \'_\' + j]) {\n let walls = countCells(board, i, j, visited);\n if (walls > max) {\n max = walls;\n x = i;\n y = j;\n }\n }\n }\n }\n\n if (x >= 0 && y >= 0) {\n max = countWalls(board, x, y, {});\n secure(board, x, y);\n }\n\n return max;\n}\n\nfunction countCells(board, i, j, infVisited) {\n var result = 0;\n\n let stack = [[i, j]];\n\n var visited = {};\n\n let neighbors = [\n [-1, 0],\n [1, 0],\n [0, -1],\n [0, 1],\n ];\n\n visited[i + \'_\' + j] = true;\n\n while (stack.length > 0) {\n let node = stack.pop();\n\n for (let n of neighbors) {\n let x = node[0] + n[0];\n let y = node[1] + n[1];\n\n if (x >= 0 && y >= 0 && x < board.length && y < board[x].length) {\n if (board[x][y] == 0) {\n if (visited[x + "_" + y]) continue;\n\n visited[x + "_" + y] = true;\n result++;\n }\n else if (board[x][y] == 1) {\n if (visited[x + "_" + y]) continue;\n\n visited[x + "_" + y] = true;\n infVisited[x + "_" + y] = true;\n stack.push([x, y]);\n }\n }\n }\n }\n\n return result;\n}\n\nfunction countWalls(board, i, j, visited) {\n var result = 0;\n\n let stack = [[i, j]];\n\n let neighbors = [\n [-1, 0],\n [1, 0],\n [0, -1],\n [0, 1],\n ];\n\n visited[i + \'_\' + j] = true;\n\n while (stack.length > 0) {\n let node = stack.pop();\n\n for (let n of neighbors) {\n let x = node[0] + n[0];\n let y = node[1] + n[1];\n\n if (x >= 0 && y >= 0 && x < board.length && y < board[x].length) {\n if (board[x][y] == 0) {\n result++;\n }\n else if (board[x][y] == 1) {\n if (visited[x + "_" + y]) continue;\n\n\n visited[x + "_" + y] = true;\n stack.push([x, y]);\n }\n }\n }\n }\n\n return result;\n}\n\nfunction secure(board, i, j) {\n let stack = [[i, j]];\n\n let neighbors = [\n [-1, 0],\n [1, 0],\n [0, -1],\n [0, 1],\n ];\n\n while (stack.length > 0) {\n let node = stack.pop();\n\n board[node[0]][node[1]] = 2;\n\n for (let n of neighbors) {\n let x = node[0] + n[0];\n let y = node[1] + n[1];\n\n if (x >= 0 && y >= 0 && x < board.length && y < board[x].length) {\n if (board[x][y] == 1) {\n stack.push([x, y]);\n }\n }\n }\n }\n}\n\nfunction spread(board) {\n var visited = {};\n\n for (let i = 0; i < board.length; i++) {\n for (let j = 0; j < board[i].length; j++) {\n if (board[i][j] == 1 && !visited[i + \'_\' + j]) {\n spreadRegion(board, i, j, visited);\n }\n }\n }\n\n for (let row of board) {\n for (let j = 0; j < row.length; j++) {\n if (row[j] == 3) row[j] = 1;\n }\n }\n}\n\nfunction spreadRegion(board, i, j, visited) {\n let stack = [[i, j]];\n\n let neighbors = [\n [-1, 0],\n [1, 0],\n [0, -1],\n [0, 1],\n ];\n\n visited[i + \'_\' + j] = true;\n\n while (stack.length > 0) {\n let node = stack.pop();\n\n for (let n of neighbors) {\n let x = node[0] + n[0];\n let y = node[1] + n[1];\n\n if (x >= 0 && y >= 0 && x < board.length && y < board[x].length) {\n if (board[x][y] == 1) {\n if (visited[x + \'_\' + y]) continue;\n visited[x + \'_\' + y] = true;\n\n stack.push([x, y]);\n }\n else if (board[x][y] == 0) board[x][y] = 3;\n }\n }\n }\n}\n``` | 0 | 0 | ['Depth-First Search', 'Graph', 'Matrix', 'JavaScript'] | 0 |
contain-virus | Python (Simple BFS) | python-simple-bfs-by-rnotappl-g4wz | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | rnotappl | NORMAL | 2024-11-25T07:59:46.680925+00:00 | 2024-11-25T07:59:46.680963+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def containVirus(self, isInfected):\n m, n, total = len(isInfected), len(isInfected[0]), 0\n\n def function(i,j):\n stack, x_cells, virus, walls = [(i,j)], set(), set(), []\n\n virus.add((i,j))\n\n while stack:\n x,y = stack.pop(0)\n\n for (nx,ny) in [(x+1,y),(x-1,y),(x,y-1),(x,y+1)]:\n if 0 <= nx < m and 0 <= ny < n:\n if isInfected[nx][ny] == 0:\n walls.append([nx,ny])\n x_cells.add((nx,ny))\n elif isInfected[nx][ny] == 1 and (nx,ny) not in virus:\n virus.add((nx,ny))\n stack.append((nx,ny))\n\n return [x_cells,walls,virus]\n\n while True:\n res, visited = [], set()\n\n for i in range(m):\n for j in range(n):\n if (i,j) not in visited and isInfected[i][j] == 1:\n ans = function(i,j)\n res.append(ans)\n visited |= ans[2]\n\n if not res:\n break \n\n for i in res:\n if i[1] == []:\n break \n\n res.sort(key = lambda x:-len(x[0]))\n\n for x,y in res[0][2]:\n isInfected[x][y] = -1\n\n for dead in res[1:]:\n for x,y in dead[0]:\n isInfected[x][y] = 1 \n\n total += len(res[0][1])\n\n return total\n``` | 0 | 0 | ['Python3'] | 0 |
contain-virus | using disjoint union | using-disjoint-union-by-arpanbiswas1812-u191 | \n\n# Code\ncpp []\nclass Solution {\npublic:\n int Uparent(int u,vector<int>& parent){\n if(u==parent[u])\n return u;\n return pare | arpanbiswas1812 | NORMAL | 2024-11-14T13:31:24.096118+00:00 | 2024-11-14T13:31:24.096141+00:00 | 12 | false | \n\n# Code\n```cpp []\nclass Solution {\npublic:\n int Uparent(int u,vector<int>& parent){\n if(u==parent[u])\n return u;\n return parent[u]=Uparent(parent[u],parent);\n }\n void union_disjoint(int u,int v,vector<int>& parent,vector<int>& size){\n int pu=Uparent(u,parent);\n int pv=Uparent(v,parent);\n\n if(pu==pv)\n return;\n if(size[pv]>size[pu]){\n parent[pu]=pv;\n size[pv]+=size[pu];\n }\n else{\n parent[pv]=pu;\n size[pu]+=size[pv];\n }\n }\n bool valid(int i,int j,int n,int m){\n return i>=0 && j>=0 && i<n && j<m;\n }\n int containVirus(vector<vector<int>>& isInfected) {\n int n=isInfected.size();\n int m=isInfected[0].size();\n int total=n*m;\n int totalWalls=0;\n \n vector<int> x={0,1,0,-1};\n vector<int> y={1,0,-1,0};\n\n \n while(true){\n vector<int> parent(n*m);\n vector<int> size(n*m,1);\n for(int i=0;i<n*m;i++){\n parent[i]=i;\n } \n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(isInfected[i][j]==1){\n\n for(int k=0;k<4;k++){\n int newx=i+x[k];\n int newy=j+y[k];\n\n if(valid(newx,newy,n,m) && isInfected[newx][newy]==1){\n union_disjoint(i*m+j,newx*m+newy,parent,size);\n }\n }\n }\n }\n }\n\n vector<unordered_set<int>> threats(n * m);\n vector<int> walls(n * m, 0);\n\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(isInfected[i][j]==1){\n int root=Uparent(i*m+j,parent);\n for(int k=0;k<4;k++){\n int newx=i+x[k];\n int newy=j+y[k];\n\n if(valid(newx,newy,n,m) && isInfected[newx][newy]==0){\n threats[root].insert(newx*m+newy);\n walls[root]++;\n }\n }\n }\n }\n }\n int maxThreat=0;\n int maxThreatCluster=-1;\n\n for(int i=0;i<n*m;i++){\n if(!threats[i].empty() && threats[i].size()>maxThreat){\n maxThreat=threats[i].size();\n maxThreatCluster=i;\n }\n }\n\n if(maxThreatCluster==-1) break;\n \n totalWalls+=walls[maxThreatCluster];\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(isInfected[i][j]==1 && Uparent(i*m+j,parent)==maxThreatCluster){\n isInfected[i][j]=-1;\n }\n }\n }\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (isInfected[i][j] == 1) {\n int root = Uparent(i * m + j, parent);\n if (root != maxThreatCluster) {\n for (int k : threats[root]) {\n isInfected[k / m][k % m] = 1; \n }\n }\n }\n }\n }\n }\n return totalWalls;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
contain-virus | easiest solution by NIKHIL DWIVEDI | easiest-solution-by-nikhil-dwivedi-by-nd-ubv2 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach: Key Concepts\nThe solution revolves around several key concepts:\n\nGrid | ND200499 | NORMAL | 2024-11-10T11:31:57.434374+00:00 | 2024-11-10T11:31:57.434429+00:00 | 21 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach: Key Concepts\nThe solution revolves around several key concepts:\n\nGrid Representation: The grid is represented as a 2D array where:\n\n0 indicates an uninfected cell,\n1 indicates an infected cell,\n2 indicates a cell that has been contained.\nRegions: A region is defined as a cluster of infected cells. The algorithm identifies these regions and assesses the number of uninfected neighboring cells.\n\nPriority Queue: This data structure is used to prioritize regions based on the number of uninfected cells adjacent to them, allowing the algorithm to contain the most threatening regions first.\n\nDepth-First Search (DFS): This technique is employed to explore the grid and gather information about infected and uninfected cells within a region.\n\nCode Structure\nThe code consists of two main classes: Solution and Region. The Solution class contains the primary logic for containing the virus, while the Region class encapsulates the properties of each infected region.\n\nSolution Class\ncontainVirus Method: This method orchestrates the containment process by identifying regions, calculating walls needed, and updating the grid.\ndfs Method: A helper method that performs a depth-first search to explore the grid and gather information about the infected and uninfected cells.\nRegion Class\nAttributes: It maintains lists of infected and uninfected cells, as well as a count of walls required for containment.\nMethods: It includes methods to add infected and uninfected cells and implements the Comparable interface to facilitate sorting in the priority queue.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n \n private static final int[][] DIR = new int[][]{\n {1, 0}, {-1, 0}, {0, 1}, {0, -1}\n };\n \n public int containVirus(int[][] isInfected) {\n int m = isInfected.length, n = isInfected[0].length;\n int ans = 0;\n \n while( true ) {\n // infected regions, sorted desc according to the number of nearby \n // uninfected nodes\n PriorityQueue<Region> pq = new PriorityQueue<Region>();\n // already visited cells\n boolean[][] visited = new boolean[m][n];\n \n // find regions\n for(int i=0; i<m; i++) {\n for(int j=0; j<n; j++) {\n \n // if current cell is infected, and it\'s not visited\n if( isInfected[i][j] != 1 || visited[i][j] ) \n continue;\n \n // we found a new region, dfs to find all the infected\n // and uninfected cells in the current region\n Region reg = new Region();\n dfs(i, j, reg, isInfected, visited, new boolean[m][n], m, n);\n \n // if there are some uninfected nodes in this region, \n // we can contain it, so add it to priority queue\n if( reg.uninfected.size() != 0)\n pq.offer(reg);\n }\n }\n \n // if there are no regions to contain, break\n if( pq.isEmpty() )\n break;\n\n // Contain region with most uninfected nodes\n Region containReg = pq.poll();\n ans += containReg.wallsRequired;\n \n // use (2) to mark a cell as contained\n for(int[] cell : containReg.infected)\n isInfected[cell[0]][cell[1]] = 2;\n \n // Spread infection to uninfected nodes in other regions\n while( !pq.isEmpty() ) {\n Region spreadReg = pq.poll();\n \n for(int[] cell : spreadReg.uninfected)\n isInfected[cell[0]][cell[1]] = 1;\n }\n }\n return ans;\n }\n \n private void dfs(int i, int j, Region reg, int[][] grid, boolean[][] visited, boolean[][] uninfectedVis, int m, int n) {\n visited[i][j] = true;\n reg.addInfected(i, j);\n \n for(int[] dir : DIR) {\n int di = i + dir[0];\n int dj = j + dir[1];\n \n // continue, if out of bounds OR contained OR already visited\n if( di < 0 || dj < 0 || di == m || dj == n || grid[di][dj] == 2 || visited[di][dj] )\n continue;\n \n // if neighbour node is not infected\n if( grid[di][dj] == 0 ) {\n // a wall will require to stop the spread from cell (i,j) to (di, dj)\n reg.wallsRequired++;\n \n // if this uninfected node is not already visited for current region\n if( !uninfectedVis[di][dj] ) {\n uninfectedVis[di][dj] = true;\n reg.addUninfected(di, dj);\n }\n } else \n dfs(di, dj, reg, grid, visited, uninfectedVis, m, n);\n }\n }\n}\nclass Region implements Comparable<Region> {\n public List<int[]> infected;\n public List<int[]> uninfected;\n public int wallsRequired;\n \n public Region() {\n infected = new ArrayList();\n uninfected = new ArrayList();\n }\n \n public void addInfected(int row, int col) {\n infected.add(new int[]{ row, col });\n }\n \n public void addUninfected(int row, int col) {\n uninfected.add(new int[]{ row, col });\n }\n \n @Override\n public int compareTo(Region r2) {\n return Integer.compare(r2.uninfected.size(), uninfected.size());\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
contain-virus | readable iterative dfs solution beats 95% | readable-iterative-dfs-solution-beats-95-lzee | Intuition\n Describe your first thoughts on how to solve this problem. \nDivide problem into subproblems, create functions for each subproblem\nput these functi | hknakbiyik10 | NORMAL | 2024-10-24T21:58:37.462475+00:00 | 2024-10-24T21:58:37.462501+00:00 | 56 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDivide problem into subproblems, create functions for each subproblem\nput these functions in global scope so that code is readable\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nkeep track of freezed cells (excluded) instead of keeping track of placed walls\n\n\n# Code\n```python3 []\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n walls_needed = 0\n excluded = set()\n\n while True:\n components = scan(isInfected, excluded)\n\n threatened_cells = threats(components, isInfected, excluded)\n mx = -1, -1\n for i in range(len(threatened_cells)):\n if threatened_cells[i] > mx[0]:\n mx = threatened_cells[i], i\n if mx[1] == -1:\n return 0\n for c_y, c_x in components[mx[1]]:\n excluded.add((c_y, c_x))\n\n walls_needed += calculate_walls_needed(components[mx[1]], isInfected)\n does_spread = simulate(components, isInfected, excluded)\n if not does_spread: break\n\n return walls_needed\n\n\ndef scan(is_infected, excluded):\n hei, wid = len(is_infected), len(is_infected[0])\n vis = [[False] * wid for _ in range(hei)]\n components = []\n\n for y in range(hei):\n for x in range(wid):\n if not is_infected[y][x] or vis[y][x] or (y, x) in excluded: continue\n stack = [(y, x)]\n component = []\n while stack:\n anc_y, anc_x = stack.pop()\n if (anc_y, anc_x) in excluded: continue\n component.append((anc_y, anc_x))\n vis[anc_y][anc_x] = True\n for dy, dx in zip((1, 0, -1, 0), (0, -1, 0, 1)):\n if not (0 <= anc_y + dy < hei and 0 <= anc_x + dx < wid and is_infected[anc_y + dy][anc_x + dx]):\n continue\n if vis[anc_y + dy][anc_x + dx]: continue\n vis[anc_y + dy][anc_x + dx] = True\n stack.append((anc_y + dy, anc_x + dx))\n components.append(component)\n return components\n\n\ndef threats(components, is_infected, excluded):\n hei, wid = len(is_infected), len(is_infected[0])\n threatened = [0] * len(components)\n for i in range(len(components)):\n counted = set()\n for c_y, c_x in components[i]:\n if (c_y, c_x) in excluded: break\n for dy, dx in zip((1, 0, -1, 0), (0, -1, 0, 1)):\n if not (0 <= c_y + dy < hei and 0 <= c_x + dx < wid): continue\n if is_infected[c_y + dy][c_x + dx]: continue\n if (c_y + dy, c_x + dx) in counted: continue\n threatened[i] += 1\n counted.add((c_y + dy, c_x + dx))\n return threatened\n\n\ndef simulate(components, is_infected, excluded):\n hei, wid = len(is_infected), len(is_infected[0])\n spread = False\n for i in range(len(components)):\n for c_y, c_x in components[i]:\n if (c_y, c_x) in excluded: continue\n for dy, dx in zip((1, 0, -1, 0), (0, -1, 0, 1)):\n if not (0 <= c_y + dy < hei and 0 <= c_x + dx < wid): continue\n if is_infected[c_y + dy][c_x + dx]: continue\n is_infected[c_y + dy][c_x + dx] = 1\n spread = True\n return spread\n\n\ndef calculate_walls_needed(component, is_infected):\n hei, wid = len(is_infected), len(is_infected[0])\n walls = 0\n\n for c_y, c_x in component:\n for dy, dx in zip((1, 0, -1, 0), (0, -1, 0, 1)):\n if not (0 <= c_y + dy < hei and 0 <= c_x + dx < wid): continue\n if not is_infected[c_y + dy][c_x + dx]:\n walls += 1\n return walls\n``` | 0 | 0 | ['Array', 'Depth-First Search', 'Matrix', 'Simulation', 'Python3'] | 1 |
contain-virus | C++ | dfs | c-dfs-by-notsojay-rg4z | Complexity\n- Time complexity: O((m * n)^2)\n\n- Space complexity: O(m * n)\n\n# Code\ncpp []\nclass Solution {\n struct RegionInfo {\n std::set<std:: | notsojay | NORMAL | 2024-10-21T06:13:46.616338+00:00 | 2024-10-21T09:19:23.280507+00:00 | 18 | false | # Complexity\n- Time complexity: O((m * n)^2)\n\n- Space complexity: O(m * n)\n\n# Code\n```cpp []\nclass Solution {\n struct RegionInfo {\n std::set<std::pair<int, int>> threat;\n std::set<std::pair<int, int>> infectedCells;\n int wallsNeeded;\n RegionInfo() : wallsNeeded(0) {}\n };\n\n static constexpr std::array<int, 5> directions = {0, 1, 0, -1, 0};\n int m, n;\n\n void dfs(int i, int j, vector<vector<int>> &isInfected, vector<vector<bool>> &visited, RegionInfo ®ion) {\n visited[i][j] = true;\n region.infectedCells.emplace(i, j);\n\n for (int d = 0; d < 4; ++d) {\n int nextI = i + directions[d];\n int nextJ = j + directions[d + 1];\n\n if (nextI < 0 || nextI >= m || nextJ < 0 || nextJ >= n) {\n continue;\n }\n \n if (isInfected[nextI][nextJ] == 0) {\n region.threat.emplace(nextI, nextJ);\n ++region.wallsNeeded;\n } else if (isInfected[nextI][nextJ] == 1 && !visited[nextI][nextJ]) {\n dfs(nextI, nextJ, isInfected, visited, region);\n }\n }\n }\n\npublic:\n int containVirus(vector<vector<int>>& isInfected) {\n m = isInfected.size();\n n = isInfected[0].size();\n int totalWalls = 0;\n\n while (true) {\n std::vector<RegionInfo> regions;\n std::vector<std::vector<bool>> visited(m, std::vector<bool>(n, false));\n\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (isInfected[i][j] == 1 && !visited[i][j]) {\n RegionInfo region;\n\n dfs(i, j, isInfected, visited, region);\n\n if (!region.threat.empty()) {\n regions.push_back(region);\n }\n }\n }\n }\n\n if (regions.empty()) {\n break;\n }\n\n auto maxThreatRegion = std::max_element(regions.begin(), regions.end(),\n [](const RegionInfo &a, const RegionInfo &b) {\n return a.threat.size() < b.threat.size();\n }\n );\n\n totalWalls += maxThreatRegion->wallsNeeded;\n\n for (const auto &[i, j] : maxThreatRegion->infectedCells) {\n isInfected[i][j] = -1;\n }\n\n for (int k = 0; k < regions.size(); ++k) {\n if (®ions[k] == &(*maxThreatRegion)) {\n continue;\n }\n for (const auto &[i, j] : regions[k].infectedCells) {\n for (int d = 0; d < 4; ++d) {\n int nextI = i + directions[d];\n int nextJ = j + directions[d + 1];\n if (nextI >= 0 && nextI < m && nextJ >= 0 && nextJ < n && isInfected[nextI][nextJ] == 0) {\n isInfected[nextI][nextJ] = 1;\n }\n }\n }\n }\n }\n\n return totalWalls;\n }\n};\n\n``` | 0 | 0 | ['Depth-First Search', 'Graph', 'Recursion', 'Matrix', 'C++'] | 0 |
contain-virus | [DFS][Python] time beats 100% solutions | dfspython-time-beats-100-solutions-by-vi-yyq1 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n1. check the district w | vikotse | NORMAL | 2024-10-17T15:39:30.213365+00:00 | 2024-10-17T15:39:30.213400+00:00 | 9 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. check the district which would be diffused.\n2. build the wall by the information from 1.\n3. diffusing for current districts.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\ndi = [-1, 0, 1, 0]\ndj = [0, 1, 0, -1]\n\ndef dfs_check(i, j, n, m, dist_no, matrix, dist, visit_dict):\n visit_dict[(i, j)] = True\n matrix[i][j] = dist_no\n for k in range(4):\n new_i = di[k] + i\n new_j = dj[k] + j\n # -1: in the wall\n if new_i >= 0 and new_i < n and new_j >= 0 and new_j < m and (new_i, new_j) not in visit_dict and matrix[new_i][new_j] != -1:\n # district is visited and could be diffused\n if matrix[new_i][new_j] == -dist_no:\n dist.wall += 1\n # district is not visited and could be diffused\n elif matrix[new_i][new_j] <= 0:\n dist.wall += 1\n dist.diffusion += 1\n matrix[new_i][new_j] = -dist_no\n # connected and diffused district\n elif matrix[new_i][new_j] > 0:\n dfs_check(new_i, new_j, n, m, dist_no, matrix, dist, visit_dict)\n\ndef dfs_build_wall(i, j, n, m, dist_no, matrix):\n matrix[i][j] = -1\n for k in range(4):\n new_i = di[k] + i\n new_j = dj[k] + j\n if new_i >= 0 and new_i < n and new_j >= 0 and new_j < m:\n if matrix[new_i][new_j] == -dist_no:\n flag = False\n for k1 in range(4):\n new_ii = di[k1] + new_i\n new_jj = dj[k1] + new_j\n if new_ii >= 0 and new_ii < n and new_jj >= 0 and new_jj < m:\n if matrix[new_ii][new_jj] > 0 and matrix[new_ii][new_jj] != dist_no:\n flag = True\n if not flag:\n matrix[new_i][new_j] = 0\n if matrix[new_i][new_j] == dist_no:\n dfs_build_wall(new_i, new_j, n, m, dist_no, matrix)\n\ndef dfs_diffuse(i, j, n, m, dist_no, matrix, visit_dict):\n visit_dict[(i, j)] = True\n matrix[i][j] = 1\n for k in range(4):\n new_i = di[k] + i\n new_j = dj[k] + j\n if new_i >= 0 and new_i < n and new_j >= 0 and new_j < m and (new_i, new_j) not in visit_dict:\n if matrix[new_i][new_j] == 0 or matrix[new_i][new_j] < -1:\n matrix[new_i][new_j] = 1\n visit_dict[(new_i, new_j)] = True\n elif matrix[new_i][new_j] == dist_no:\n dfs_diffuse(new_i, new_j, n, m, dist_no, matrix, visit_dict)\n\nclass Dist:\n def __init__(self, i, j, wall, diffusion):\n self.i = i\n self.j = j\n self.wall = wall\n self.diffusion = diffusion\n\nclass Solution:\n def containVirus(self, matrix: List[List[int]]) -> int:\n n = len(matrix)\n m = len(matrix[0])\n total_wall = 0\n while True:\n # calculate diffusion\n dist_no = 2\n dist_dict = {}\n max_diffusion = 0\n max_dist_no = 0\n visit_dict = {}\n for i in range(n):\n for j in range(m):\n if matrix[i][j] == 1 or matrix[i][j] >= dist_no:\n dist = Dist(i, j, 0, 0)\n dfs_check(i, j, n, m, dist_no, matrix, dist, visit_dict)\n if dist.diffusion > max_diffusion:\n max_diffusion = dist.diffusion\n max_dist_no = dist_no\n dist_dict[dist_no] = dist\n dist_no += 1\n\n if max_diffusion == 0:\n break\n\n # calculate wall\n total_wall += dist_dict[max_dist_no].wall\n\n # build wall\n dfs_build_wall(dist_dict[max_dist_no].i, dist_dict[max_dist_no].j, n, m, max_dist_no, matrix)\n\n # diffuse\n del dist_dict[max_dist_no]\n visit_dict = {}\n for dist_no, dist in dist_dict.items():\n dfs_diffuse(dist.i, dist.j, n, m, dist_no, matrix, visit_dict)\n return total_wall\n``` | 0 | 0 | ['Python3'] | 0 |
contain-virus | Beats 0 % | beats-0-by-stack_exchange-dpzt | Intuition\nThe goal of the problem is to contain a viral outbreak on a grid by building walls around the most threatening regions. The algorithm needs to identi | Stack_Exchange | NORMAL | 2024-10-01T10:55:25.766805+00:00 | 2024-10-01T10:55:25.766828+00:00 | 7 | false | ### Intuition\nThe goal of the problem is to contain a viral outbreak on a grid by building walls around the most threatening regions. The algorithm needs to identify these regions, calculate how many walls are required to contain them, and then process the spread of the infection accordingly.\n\n### Approach\n1. **Identifying Regions**: We iterate over the grid to find all infected blocks (denoted by `1`). For each infected block, we perform a depth-first search (DFS) to count its size and potential spread.\n \n2. **Selecting the Most Threatening Block**: After identifying all infected blocks, we determine which block poses the greatest threat based on its potential spread.\n\n3. **Building Walls**: For the most threatening block, we calculate how many walls are required to contain it. We then mark that block as contained.\n\n4. **Contamination Spread**: After building the walls, we mark adjacent empty cells to potentially become infected in the next iteration and update the grid.\n\n5. **Repeating the Process**: We repeat the above steps until there are no more infected blocks.\n\n### Complexity\n- **Time Complexity**: The time complexity is approximately \\(O(m \\times n)\\) in the worst case, where \\(m\\) is the number of rows and \\(n\\) is the number of columns. This is due to the multiple passes over the grid for DFS and processing.\n\n- **Space Complexity**: The space complexity is \\(O(m \\times n)\\) due to the additional data structures used (like the visited grid and temporary infection markings).\n\n### Code Breakdown\n\n```cpp\nclass Solution {\npublic:\n // Main function to contain the virus\n int containVirus(vector<vector<int>>& inf) {\n int m = inf.size(); // Number of rows in the grid\n int n = inf[0].size(); // Number of columns in the grid\n int ans = FindWalls(m, n, inf); // Call the function to find and build walls\n return ans; // Return the total number of walls built\n }\n```\n- **`containVirus`**: Initializes grid dimensions and calls `FindWalls`.\n\n---\n\n```cpp\n // Function to find and build walls around the most threatening infection region\n int FindWalls(int m, int n, vector<vector<int>>& inf) {\n int ans = 0; // Total walls built\n int maxima = 0; // Maximum potential spread from a block\n int start_x = 0; // X coordinate of the block to process\n int start_y = 0; // Y coordinate of the block to process\n\n while (true) { // Continue until there are no infected regions\n maxima = 0; // Reset maximum for this iteration\n int local_ans = 0; // Walls needed for the current block\n vector<vector<int>> v(m, vector<int>(n, 0)); // Visited grid for DFS\n\n // Iterate through the grid to find all infected blocks\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n // If the cell is infected and not visited\n if (inf[i][j] == 1 && v[i][j] == 0) {\n initialize(v, m, n, inf); // Initialize visited grid\n local_ans = blocks(i, j, v, inf, m, n); // Count the size of the block\n if (local_ans > maxima) {\n start_x = i; // Update coordinates of the largest block\n start_y = j;\n }\n maxima = max(maxima, local_ans); // Update maximum spread\n }\n }\n }\n\n // If no infected block is found, exit the loop\n if (maxima == 0) return ans;\n\n // Reset visited grid for the next block\n for (int i = 0; i < m; i++)\n for (int j = 0; j < n; j++)\n v[i][j] = 0;\n\n // Count the walls needed to contain the largest spread block\n ans += blockToSpread(start_x, start_y, v, inf, m, n);\n vector<vector<int>> G(m, vector<int>(n, 0)); // Grid to track dismantling\n Dismantle(start_x, start_y, inf, G, m, n); // Dismantle the infected block\n ContaminateMarking(inf, m, n); // Mark adjacent cells for contamination\n Contaminate(inf, m, n); // Update grid after contamination\n }\n }\n```\n- **`FindWalls`**: This function identifies infected regions and decides where to build walls.\n\n - **Inner Loop**: Iterates over the grid to find infected blocks.\n - **DFS (`blocks`)**: Used to count the size of each infected block.\n - **Wall Counting**: Calculates the number of walls needed for the most threatening block.\n - **Contamination Management**: Calls functions to dismantle infected areas and mark surrounding cells for contamination.\n\n---\n\n```cpp\n // Initialize the visited grid\n void initialize(vector<vector<int>>& v, int m, int n, vector<vector<int>>& inf) {\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n // Mark non-infected cells as unvisited\n if (inf[i][j] == 0)\n v[i][j] = 0;\n }\n }\n }\n```\n- **`initialize`**: Resets the visited grid to track which cells have been processed.\n\n---\n\n```cpp\n // DFS to count the size of the infected block starting from (x, y)\n int blocks(int x, int y, vector<vector<int>>& v, vector<vector<int>>& inf, int m, int n) {\n // Out of bounds check\n if (x < 0 || x >= m || y < 0 || y >= n)\n return 0;\n\n // If already visited, return\n if (v[x][y] == 1)\n return 0;\n\n v[x][y] = 1; // Mark the cell as visited\n\n // If the cell is empty, count it as a potential spread\n if (inf[x][y] == 0)\n return 1;\n // If the cell has a wall, it can\'t be counted\n if (inf[x][y] == -1)\n return 0;\n\n int sum = 0; // To count the size of the block\n // If the cell is infected, continue DFS to adjacent cells\n if (inf[x][y] == 1) {\n sum += blocks(x + 1, y, v, inf, m, n);\n sum += blocks(x - 1, y, v, inf, m, n);\n sum += blocks(x, y - 1, v, inf, m, n);\n sum += blocks(x, y + 1, v, inf, m, n);\n }\n return sum; // Return the total count\n }\n```\n- **`blocks`**: Performs a depth-first search to count the number of infected cells in a block.\n\n---\n\n```cpp\n // Count potential spread from a block starting at (x, y)\n int blockToSpread(int x, int y, vector<vector<int>>& v, vector<vector<int>>& inf, int m, int n) {\n // Out of bounds check\n if (x < 0 || x >= m || y < 0 || y >= n)\n return 0;\n\n // If the cell is empty, count it as potential spread\n if (inf[x][y] == 0) {\n return 1;\n }\n\n // If already visited, return\n if (v[x][y] == 1)\n return 0;\n\n v[x][y] = 1; // Mark the cell as visited\n\n int sum = 0; // To count potential spread\n // If the cell is infected, continue to adjacent cells\n if (inf[x][y] == 1) {\n sum += blockToSpread(x + 1, y, v, inf, m, n);\n sum += blockToSpread(x - 1, y, v, inf, m, n);\n sum += blockToSpread(x, y - 1, v, inf, m, n);\n sum += blockToSpread(x, y + 1, v, inf, m, n);\n }\n return sum; // Return the total count\n }\n```\n- **`blockToSpread`**: Similar to `blocks`, but focuses on counting how many adjacent empty cells can potentially become infected.\n\n---\n\n```cpp\n // Dismantle the infected block by marking it with walls\n void Dismantle(int x, int y, vector<vector<int>>& inf, vector<vector<int>>& G, int m, int n) {\n // Out of bounds check\n if (x < 0 || x >= m || y < 0 || y >= n)\n return;\n\n // If already processed, return\n if (G[x][y] == 1)\n return;\n\n G[x][y] = 1; // Mark this cell as processed\n\n // If the cell is infected, mark it as a wall\n if (inf[x][y] == 1\n\n) {\n inf[x][y] = -1; // Mark as wall\n // Recursively dismantle adjacent cells\n Dismantle(x + 1, y, inf, G, m, n);\n Dismantle(x - 1, y, inf, G, m, n);\n Dismantle(x, y + 1, inf, G, m, n);\n Dismantle(x, y - 1, inf, G, m, n);\n } else {\n return; // Return if it\'s not infected\n }\n }\n```\n- **`Dismantle`**: Marks infected cells as walls (`-1`), effectively containing the region.\n\n---\n\n```cpp\n // Mark adjacent cells of infected blocks for contamination\n void ContaminateMarking(vector<vector<int>>& inf, int m, int n) {\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n // If the cell is infected, mark its empty neighbors\n if (inf[i][j] == 1) {\n ContaminateBlockMarking(i + 1, j, inf, m, n);\n ContaminateBlockMarking(i - 1, j, inf, m, n);\n ContaminateBlockMarking(i, j + 1, inf, m, n);\n ContaminateBlockMarking(i, j - 1, inf, m, n);\n }\n }\n }\n return; // End of function\n }\n```\n- **`ContaminateMarking`**: Marks adjacent empty cells to indicate they can become infected in the next iteration.\n\n---\n\n```cpp\n // Mark an adjacent empty cell as temporarily infected\n void ContaminateBlockMarking(int x, int y, vector<vector<int>>& inf, int m, int n) {\n // Out of bounds check\n if (x < 0 || x >= m || y < 0 || y >= n)\n return;\n\n // If the cell is empty, mark it as temporarily infected\n if (inf[x][y] == 0)\n inf[x][y] = -2;\n\n return; // End of function\n }\n```\n- **`ContaminateBlockMarking`**: Marks an empty cell as temporarily infected (`-2`).\n\n---\n\n```cpp\n // Convert temporarily infected cells back to infected\n void Contaminate(vector<vector<int>>& inf, int m, int n) {\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n // If a cell is temporarily infected, convert it to infected\n if (inf[i][j] == -2)\n inf[i][j] = 1;\n }\n }\n return; // End of function\n }\n};\n```\n- **`Contaminate`**: Updates the grid by converting temporarily infected cells back to the infected state.\n\n### Summary\nThis code effectively identifies and contains viral outbreaks on a grid using DFS to track and manage infections. By systematically dismantling the most threatening infected blocks and managing contamination, the algorithm efficiently calculates the number of walls needed to contain the virus.\n\n### Full Code\n\n\n```cpp\nclass Solution {\npublic:\n // Main function to contain the virus\n int containVirus(vector<vector<int>>& inf) {\n int m = inf.size(); // Get the number of rows in the grid\n int n = inf[0].size(); // Get the number of columns in the grid\n int ans = FindWalls(m, n, inf); // Start the process to find and build walls\n return ans; // Return the total number of walls built\n }\n\n // Function to find and build walls around the most threatening infection region\n int FindWalls(int m, int n, vector<vector<int>>& inf) {\n int ans = 0; // Total walls built\n int maxima = 0; // Maximum potential spread from a block\n int start_x = 0; // X coordinate of the most threatening block\n int start_y = 0; // Y coordinate of the most threatening block\n\n while (true) { // Loop until there are no more infected regions\n maxima = 0; // Reset maximum size for this iteration\n int local_ans = 0; // Walls needed for the current block\n vector<vector<int>> v(m, vector<int>(n, 0)); // Visited grid for tracking\n\n // Iterate through the grid to find all infected blocks\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n // If the cell is infected and not visited\n if (inf[i][j] == 1 && v[i][j] == 0) {\n initialize(v, m, n, inf); // Initialize visited grid\n local_ans = blocks(i, j, v, inf, m, n); // Count the size of this block\n if (local_ans > maxima) { // Check if it\'s the largest\n start_x = i; // Update coordinates for the largest block\n start_y = j;\n }\n maxima = max(maxima, local_ans); // Update the maximum size found\n }\n }\n }\n\n // If no infected block is found, exit the loop\n if (maxima == 0) return ans;\n\n // Reset visited grid for the next block\n for (int i = 0; i < m; i++)\n for (int j = 0; j < n; j++)\n v[i][j] = 0;\n\n // Count the walls needed to contain the largest spread block\n ans += blockToSpread(start_x, start_y, v, inf, m, n); // Add walls count\n vector<vector<int>> G(m, vector<int>(n, 0)); // Grid to track dismantling\n Dismantle(start_x, start_y, inf, G, m, n); // Mark the infected block as walls\n ContaminateMarking(inf, m, n); // Mark adjacent cells for possible contamination\n Contaminate(inf, m, n); // Update grid with new infections\n }\n }\n\n // Function to initialize the visited grid\n void initialize(vector<vector<int>>& v, int m, int n, vector<vector<int>>& inf) {\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n // Mark non-infected cells as unvisited\n if (inf[i][j] == 0)\n v[i][j] = 0;\n }\n }\n }\n\n // DFS to count the size of the infected block starting from (x, y)\n int blocks(int x, int y, vector<vector<int>>& v, vector<vector<int>>& inf, int m, int n) {\n // Out of bounds check\n if (x < 0 || x >= m || y < 0 || y >= n)\n return 0; // Invalid cell\n\n // If already visited, return\n if (v[x][y] == 1)\n return 0; // Already counted\n\n v[x][y] = 1; // Mark the cell as visited\n\n // If the cell is empty, count it as a potential spread\n if (inf[x][y] == 0)\n return 1; // Empty cell, count it\n\n // If the cell has a wall, it can\'t be counted\n if (inf[x][y] == -1)\n return 0; // Wall cell, don\'t count it\n\n int sum = 0; // To count the size of the block\n // If the cell is infected, continue DFS to adjacent cells\n if (inf[x][y] == 1) {\n sum += blocks(x + 1, y, v, inf, m, n); // Down\n sum += blocks(x - 1, y, v, inf, m, n); // Up\n sum += blocks(x, y - 1, v, inf, m, n); // Left\n sum += blocks(x, y + 1, v, inf, m, n); // Right\n }\n return sum; // Return the total count of this block\n }\n\n // Count potential spread from a block starting at (x, y)\n int blockToSpread(int x, int y, vector<vector<int>>& v, vector<vector<int>>& inf, int m, int n) {\n // Out of bounds check\n if (x < 0 || x >= m || y < 0 || y >= n)\n return 0; // Invalid cell\n\n // If the cell is empty, count it as potential spread\n if (inf[x][y] == 0) {\n return 1; // Count empty cell\n }\n\n // If already visited, return\n if (v[x][y] == 1)\n return 0; // Already counted\n\n v[x][y] = 1; // Mark the cell as visited\n\n int sum = 0; // To count potential spread\n // If the cell is infected, continue to adjacent cells\n if (inf[x][y] == 1) {\n sum += blockToSpread(x + 1, y, v, inf, m, n); // Down\n sum += blockToSpread(x - 1, y, v, inf, m, n); // Up\n sum += blockToSpread(x, y - 1, v, inf, m, n); // Left\n sum += blockToSpread(x, y + 1, v, inf, m, n); // Right\n }\n return sum; // Return the total count of potential spread\n }\n\n // Dismantle the infected block by marking it with walls\n void Dismantle(int x, int y, vector<vector<int>>& inf, vector<vector<int>>& G, int m, int n) {\n // Out of bounds check\n if (x < 0 || x >= m || y < 0 || y >= n)\n return; // Invalid cell\n\n // If already processed, return\n if (G[x][y] == 1)\n return; // Already processed\n\n G[x][y] = 1; // Mark this cell as processed\n\n // If the cell is infected, mark it as a wall\n if (inf[x][y] == 1) {\n inf[x][y] = -1; // Mark as wall\n // Recursively dismantle adjacent cells\n Dismantle(x + 1, y, inf, G, m, n); // Down\n Dismantle(x - 1, y, inf, G, m, n); // Up\n Dismantle(x, y + 1, inf, G, m, n); // Right\n Dismantle(x, y - 1, inf, G, m, n); // Left\n }\n }\n\n // Mark adjacent cells of infected blocks for contamination\n void ContaminateMarking(vector<vector<int>>& inf, int m, int n) {\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n // If the cell is infected, mark its empty neighbors\n if (inf[i][j] == 1) {\n ContaminateBlockMarking(i + 1, j, inf, m, n); // Down\n ContaminateBlockMarking(i - 1, j, inf, m, n); // Up\n ContaminateBlockMarking(i, j + 1, inf, m, n); // Right\n ContaminateBlockMarking(i, j - 1, inf, m, n); // Left\n }\n }\n }\n }\n\n // Mark an adjacent empty cell as temporarily infected\n void ContaminateBlockMarking(int x, int y, vector<vector<int>>& inf, int m, int n) {\n // Out of bounds check\n if (x < 0 || x >= m || y < 0 || y >= n)\n return; // Invalid cell\n\n // If the cell is empty, mark it as temporarily infected\n if (inf[x][y] == 0)\n inf[x][y] = -2; // Mark temporarily infected\n }\n\n // Convert temporarily infected cells back to infected\n void Contaminate(vector<vector<int>>& inf, int m, int n) {\n for (int\n\n i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n // If a cell is temporarily infected, convert it to infected\n if (inf[i][j] == -2)\n inf[i][j] = 1; // Change back to infected\n }\n }\n }\n};\n```\n\n\n | 0 | 0 | ['C++'] | 0 |
contain-virus | 749. Contain Virus | 749-contain-virus-by-mimiseksimi-qji5 | Intuition\nThe problem requires simulating the spread of a virus and containment efforts day by day. We need to identify the region that threatens the most unin | mimiseksimi | NORMAL | 2024-09-06T14:43:54.923587+00:00 | 2024-09-06T14:43:54.923624+00:00 | 9 | false | # Intuition\nThe problem requires simulating the spread of a virus and containment efforts day by day. We need to identify the region that threatens the most uninfected cells each day, quarantine it, and continue this process until all infected regions are contained or the entire grid is infected.\n\n# Approach\n1. Implement a function to find all distinct virus regions using DFS.\n2. For each region, calculate the number of walls needed and the number of cells it threatens.\n3. Quarantine the region that threatens the most cells by marking it with a special value.\n4. Simulate the spread of the virus in non-quarantined regions.\n5. Repeat steps 1-4 until no more spreading is possible.\n\n# Complexity\n- Time complexity: O(m * n * (m + n)), where m and n are the dimensions of the grid. In the worst case, we might need to traverse the entire grid multiple times.\n- Space complexity: O(m * n) for the recursion stack in DFS and to store the visited cells.\n\n# Code\n```python3\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n def dfs(i, j, visited, region, frontier):\n if (i, j) in visited:\n return 0\n visited.add((i, j))\n region.add((i, j))\n walls = 0\n for ni, nj in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]:\n if 0 <= ni < m and 0 <= nj < n:\n if isInfected[ni][nj] == 1:\n walls += dfs(ni, nj, visited, region, frontier)\n elif isInfected[ni][nj] == 0:\n frontier.add((ni, nj))\n walls += 1\n return walls\n\n m, n = len(isInfected), len(isInfected[0])\n total_walls = 0\n\n while True:\n visited = set()\n regions = []\n frontiers = []\n walls = []\n\n for i in range(m):\n for j in range(n):\n if isInfected[i][j] == 1 and (i, j) not in visited:\n region = set()\n frontier = set()\n region_walls = dfs(i, j, visited, region, frontier)\n regions.append(region)\n frontiers.append(frontier)\n walls.append(region_walls)\n\n if not regions:\n break\n\n max_frontier = max(range(len(frontiers)), key=lambda i: len(frontiers[i]))\n total_walls += walls[max_frontier]\n\n for i, region in enumerate(regions):\n if i != max_frontier:\n for r, c in region:\n for nr, nc in [(r+1, c), (r-1, c), (r, c+1), (r, c-1)]:\n if 0 <= nr < m and 0 <= nc < n and isInfected[nr][nc] == 0:\n isInfected[nr][nc] = 1\n\n for r, c in regions[max_frontier]:\n isInfected[r][c] = -1\n\n return total_walls | 0 | 0 | ['Python3'] | 0 |
contain-virus | Simulation - BFS | simulation-bfs-by-a4yan1-q4ch | Code\ncpp []\nclass Solution {\npublic:\n int drow[4] = {-1,0,1,0};\n int dcol[4] = {0,1,0,-1};\n int no_of_cells_infected(vector<vector<int>> &grid,in | a4yan1 | NORMAL | 2024-09-06T05:31:31.624142+00:00 | 2024-09-06T05:31:31.624181+00:00 | 6 | false | # Code\n```cpp []\nclass Solution {\npublic:\n int drow[4] = {-1,0,1,0};\n int dcol[4] = {0,1,0,-1};\n int no_of_cells_infected(vector<vector<int>> &grid,int row,int col,vector<vector<int>> &vis,vector<vector<int>> &already){\n vis[row][col] = 1;\n queue<pair<int,int>> q;\n q.push({row,col});\n vector<pair<int,int>> l;\n int cnt = 0;\n while(!q.empty()){\n auto it = q.front();\n int r = it.first;\n int c = it.second;\n q.pop();\n for(int i=0;i<4;i++){\n int nrow = r + drow[i];\n int ncol = c + dcol[i];\n if(nrow >= 0 && nrow < grid.size() && ncol >= 0 && ncol < grid[0].size() && !vis[nrow][ncol] && !already[nrow][ncol]){\n if(grid[nrow][ncol]) q.push({nrow,ncol});\n else{\n cnt++;\n l.push_back({nrow,ncol});\n }\n vis[nrow][ncol] = 1;\n }\n }\n }\n for(auto it: l) vis[it.first][it.second] = 0;\n return cnt;\n }\n pair<int,int> find_area(vector<vector<int>> &grid,vector<vector<int>> &already){\n int n = grid.size(); int m = grid[0].size();\n pair<int,int> pair = {-1,-1}; int maxi = 0;\n vector<vector<int>> vis(n,vector<int>(m,0));\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(grid[i][j] && !already[i][j] && !vis[i][j]){\n int tmp = maxi;\n maxi = max(no_of_cells_infected(grid,i,j,vis,already),maxi);\n if(tmp != maxi) pair = {i,j};\n }\n }\n }\n return pair;\n }\n int containVirus(vector<vector<int>>& grid) {\n int n = grid.size(); int m = grid[0].size();\n vector<vector<int>> vis(n,vector<int>(m,0));\n int cnt = 0;\n while(true){\n pair<int,int> coor = find_area(grid,vis);\n if(coor.first == -1 || coor.second == -1) break;\n cnt += make_walls(grid,vis,coor.first,coor.second);\n update_grid(grid,vis);\n }\n return cnt;\n }\n int make_walls(vector<vector<int>> &grid, vector<vector<int>> &vis, int start_row, int start_col){\n int n = grid.size(); int m = grid[0].size();\n vis[start_row][start_col] = 1;\n queue<pair<int,int>> q;\n q.push({start_row,start_col});\n int cnt = 0;\n while(!q.empty()){\n auto it = q.front();\n int row = it.first;\n int col = it.second;\n q.pop();\n for(int i=0;i<4;i++){\n int nrow = row + drow[i];\n int ncol = col + dcol[i];\n if(nrow >= 0 && ncol >= 0 && nrow < n && ncol < m && !vis[nrow][ncol]){\n if(grid[nrow][ncol]){\n vis[nrow][ncol] = 1;\n q.push({nrow,ncol});\n }else cnt++;\n }\n }\n }\n return cnt;\n }\n void update_grid(vector<vector<int>> &grid,vector<vector<int>> &vis){\n int n = grid.size(); int m = grid[0].size();\n vector<vector<int>> vis_comp(n,vector<int>(m,0));\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(grid[i][j] && !vis_comp[i][j] && !vis[i][j]){ // is one and not a newly added cell and not walled one\n for(int l=0;l<4;l++){\n int nrow = i + drow[l];\n int ncol = j + dcol[l];\n if(nrow >= 0 && ncol >= 0 && nrow < n && ncol < m && !vis_comp[nrow][ncol] && !grid[nrow][ncol] && !vis[nrow][ncol]){\n grid[nrow][ncol] = 1;\n vis_comp[nrow][ncol] = 1;\n }\n }\n }\n }\n }\n }\n};\n``` | 0 | 0 | ['Breadth-First Search', 'Matrix', 'Simulation', 'C++'] | 0 |
contain-virus | Swift - Contain Virus | swift-contain-virus-by-ksmirnovnn-vn5g | \n\nclass Solution {\n func containVirus(_ isInfected: [[Int]]) -> Int {\n // Copy of the original grid to modify during processing\n var grid | ksmirnovnn | NORMAL | 2024-07-18T19:35:33.298379+00:00 | 2024-07-18T19:35:33.298398+00:00 | 3 | false | \n```\nclass Solution {\n func containVirus(_ isInfected: [[Int]]) -> Int {\n // Copy of the original grid to modify during processing\n var grid = isInfected\n // Directions for moving up, down, left, and right\n let directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n // Variable to keep track of the total number of walls used\n var totalWalls = 0\n \n // Depth-First Search (DFS) function to explore a viral region\n func dfs(_ i: Int, _ j: Int, _ region: inout Set<[Int]>, _ frontier: inout Set<[Int]>, _ walls: inout Int) {\n let n = grid.count\n let m = grid[0].count\n // Stack for DFS traversal\n var stack = [(i, j)]\n region.insert([i, j])\n var idx = 0\n \n while idx < stack.count {\n let (x, y) = stack[idx]\n idx += 1\n \n for direction in directions {\n let newX = x + direction.0\n let newY = y + direction.1\n \n // Check if the new position is within bounds\n if newX >= 0 && newX < n && newY >= 0 && newY < m {\n if grid[newX][newY] == 1 && !region.contains([newX, newY]) {\n // If the new cell is infected and not yet visited in this region\n stack.append((newX, newY))\n region.insert([newX, newY])\n } else if grid[newX][newY] == 0 {\n // If the new cell is uninfected (part of the frontier)\n frontier.insert([newX, newY])\n walls += 1\n }\n }\n }\n }\n }\n \n // Main loop to process the grid until no more infections can spread\n while true {\n var regions = [Set<[Int]>]()\n var frontiers = [Set<[Int]>]()\n var wallsList = [Int]()\n \n let n = grid.count\n let m = grid[0].count\n var visited = Set<[Int]>()\n \n // Identify all viral regions and their frontiers\n for i in 0..<n {\n for j in 0..<m {\n if grid[i][j] == 1 && !visited.contains([i, j]) {\n var region = Set<[Int]>()\n var frontier = Set<[Int]>()\n var walls = 0\n dfs(i, j, ®ion, &frontier, &walls)\n for cell in region {\n visited.insert(cell)\n }\n regions.append(region)\n frontiers.append(frontier)\n wallsList.append(walls)\n }\n }\n }\n \n // If there are no more viral regions, break the loop\n if regions.isEmpty {\n break\n }\n \n // Find the region with the largest frontier\n var maxFrontierIdx = 0\n for i in 1..<frontiers.count {\n if frontiers[i].count > frontiers[maxFrontierIdx].count {\n maxFrontierIdx = i\n }\n }\n \n // Add the walls needed for the most dangerous region to the total count\n totalWalls += wallsList[maxFrontierIdx]\n \n // Quarantine the most dangerous region by marking its cells with -1\n for cell in regions[maxFrontierIdx] {\n grid[cell[0]][cell[1]] = -1\n }\n \n // Spread the virus in the remaining regions\n for i in 0..<regions.count {\n if i != maxFrontierIdx {\n for cell in frontiers[i] {\n grid[cell[0]][cell[1]] = 1\n }\n }\n }\n }\n \n return totalWalls\n }\n}\n\n``` | 0 | 0 | ['Swift'] | 0 |
contain-virus | Simple DFS based component counting + Implementation skills | simple-dfs-based-component-counting-impl-gol2 | Intuition\nSimple DFS based component counting + Implementation skills.\n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ashutoshdayal | NORMAL | 2024-06-05T10:44:10.395724+00:00 | 2024-06-05T10:44:10.395747+00:00 | 56 | false | # Intuition\nSimple DFS based component counting + Implementation skills.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nusing pii=pair<int,int>;\n\n#define F first\n#define S second\n\nint dx[]={1,-1,0,0};\nint dy[]={0,0,1,-1};\n\nclass Solution {\nprivate:\nvoid print_grid(vector<vector<int>>& grid) {\n int m=grid.size(),n=grid[0].size();\n for (int i=0;i<m;i++) { for(int j=0;j<n;j++) {\n cout<<(grid[i][j]?"O":".");\n } cout<<endl; }\n}\n\nbool simulate_step(vector<vector<int>>& grid) {//O(mn) //is_quarantined?\n int m=grid.size(),n=grid[0].size();\n bool any_infection=0, fully_filled=1;\n vector<pii> todo;\n for (int i=0;i<m;i++) for (int j=0;j<n;j++) {\n if (grid[i][j]==1) { //infected\n any_infection=1;\n for (int k=0;k<4;k++) { \n int x_=i+dx[k], y_=j+dy[k];\n if (x_>=0&&x_<m&&y_>=0&&y_<n&&grid[x_][y_]==0) todo.push_back({x_,y_});\n }\n }\n if (fully_filled&&grid[i][j]==0)fully_filled=0;\n }\n for (auto _:todo)grid[_.F][_.S]=1;\n return !any_infection || fully_filled;\n}\n\nclass cluster {\npublic:\n set<pii> infected;\n set<pii> conn_uninfected;\n int wallcnt=0;\n};\n\nvoid dfs(int x, int y, vector<vector<int>>& grid, cluster &comp, vector<vector<bool>> &vis) {//O(mn)\n int m=grid.size(),n=grid[0].size();\n if (x<0||x>=m||y<0||y>=n||vis[x][y]||grid[x][y]==2)return;\n\n if (grid[x][y]==0) {\n comp.conn_uninfected.insert({x,y});\n comp.wallcnt++;\n return;\n }\n comp.infected.insert({x,y});\n vis[x][y]=1;\n for (int i=0;i<4;i++) {\n int x_=x+dx[i],y_=y+dy[i];\n dfs(x_,y_,grid,comp,vis);\n }\n}\n\nvector<cluster> get_infected_components(vector<vector<int>>& grid) { //O(mn)\n vector<cluster> ans;\n int m=grid.size(),n=grid[0].size();\n vector<vector<bool>> vis;vis.assign(m,vector<bool>(n,0));\n for (int i=0;i<m;i++) for (int j=0;j<n;j++) {\n if (grid[i][j]==1 && !vis[i][j]) {\n cluster comp; \n dfs(i,j,grid,comp,vis);\n ans.push_back(comp);\n }\n }\n return ans;\n}\npublic:\nint containVirus(vector<vector<int>>& grid) {\n int walls=0;\n do {\n auto comps=get_infected_components(grid);\n int max_index=0;\n for (int i=0;i<comps.size();i++)\n if (comps[max_index].conn_uninfected.size()<comps[i].conn_uninfected.size())max_index=i;\n if (comps.size()) {\n walls+=comps[max_index].wallcnt;\n for (auto _:comps[max_index].infected) grid[_.F][_.S]=2;\n }\n } while (!simulate_step(grid));\n return walls;\n}\n\n};\n``` | 0 | 0 | ['C++'] | 0 |
contain-virus | good | good-by-gjwlsgur4866-3w22 | Approach\n1. dfs -> \uBAA8\uB4E0 \uBC14\uC774\uB7EC\uC2A4 \uC9C0\uC5ED, \uADF8 \uC9C0\uC5ED\uC774 \uBBF8\uCE58\uB294 \uC704\uD611, \uACA9\uB9AC\uD558\uB294 \uB3 | gjwlsgur4866 | NORMAL | 2024-05-29T01:03:55.409762+00:00 | 2024-05-29T01:03:55.409780+00:00 | 28 | false | # Approach\n1. dfs -> \uBAA8\uB4E0 \uBC14\uC774\uB7EC\uC2A4 \uC9C0\uC5ED, \uADF8 \uC9C0\uC5ED\uC774 \uBBF8\uCE58\uB294 \uC704\uD611, \uACA9\uB9AC\uD558\uB294 \uB370 \uD544\uC694\uD55C \uBCBD\uC758 \uC218\n2. \uC704\uD611 \uAC00\uC7A5 \uD070 \uACF3 \uACA9\uB9AC = \uBCBD \uC138\uC6B0\uAE30 -> isInfected[i][j] = -1\n3. \uBC14\uC774\uB7EC\uC2A4 \uD655\uC0B0\n\n# Code\n```\nclass Solution {\n int[] dx = {1, 0, -1, 0};\n int[] dy = {0, 1, 0, -1};\n int n, m;\n public int containVirus(int[][] isInfected) {\n // \uBC14\uC774\uB7EC\uC2A4 \uC9C0\uC5ED \uD655\uC778\n // \uD655\uC0B0\uD55C\uB2E4\uBA74 \uD53C\uD574\uAC00 \uAC00\uC7A5 \uD070 \uACF3 \uCC3E\n // \uBCBD \uC138\uC6B0\uAE30\n // \uBC14\uC774\uB7EC\uC2A4 \uD655\uC0B0\n n = isInfected.length;\n m = isInfected[0].length;\n int result = 0;\n \n while (true) {\n List<Set<Integer>> regions = new ArrayList<>();\n List<Set<Integer>> threats = new ArrayList<>();\n List<Integer> walls = new ArrayList<>();\n boolean[][] visited = new boolean[n][m];\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (isInfected[i][j] == 1 && !visited[i][j]) {\n Set<Integer> region = new HashSet<>();\n Set<Integer> threat = new HashSet<>();\n int[] wall = new int[1];\n dfs(isInfected, visited, i, j, region, threat, wall);\n regions.add(region);\n threats.add(threat);\n walls.add(wall[0]);\n }\n }\n }\n\n if (regions.isEmpty()) break;\n\n int maxThreatIdx = 0;\n for (int i = 0; i < threats.size(); i++) {\n if (threats.get(i).size() > threats.get(maxThreatIdx).size()) {\n maxThreatIdx = i;\n }\n }\n\n result += walls.get(maxThreatIdx);\n\n for (int i = 0; i < regions.size(); i++) {\n if (i == maxThreatIdx) {\n for (int num : regions.get(i)) {\n int y = num / m, x = num % m;\n isInfected[y][x] = -1;\n }\n } else {\n for (int num : threats.get(i)) {\n int y = num / m, x = num % m;\n isInfected[y][x] = 1;\n }\n }\n }\n }\n\n return result;\n }\n\n private void dfs(int[][] isInfected, boolean[][] visited, int y, int x, Set<Integer> region, Set<Integer> threat, int[] wall) {\n if (y < 0 || x < 0 || y >= n || x >= m || visited[y][x] || isInfected[y][x] != 1) return;\n\n visited[y][x] = true;\n region.add(y * m + x);\n\n for (int d = 0; d < 4; d++) {\n int ny = y + dy[d];\n int nx = x + dx[d];\n if (ny >= 0 && ny < n && nx >= 0 && nx < m) {\n if (isInfected[ny][nx] == 0) {\n threat.add(ny * m + nx);\n wall[0]++;\n } else if (isInfected[ny][nx] == 1 && !visited[ny][nx]) {\n dfs(isInfected, visited, ny, nx, region, threat, wall);\n }\n }\n }\n }\n}\n``` | 0 | 0 | ['Simulation', 'Java'] | 0 |
contain-virus | Python Hard | python-hard-by-lucasschnee-aavm | \nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n M, N = len(isInfected), len(isInfected[0])\n directions = [(0 | lucasschnee | NORMAL | 2024-05-23T03:31:47.747117+00:00 | 2024-05-23T03:31:47.747160+00:00 | 12 | false | ```\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n M, N = len(isInfected), len(isInfected[0])\n directions = [(0, 1), (0, -1), (-1, 0), (1, 0)]\n marked = defaultdict(set)\n walls = 0\n\n def bfs(x, y):\n q = deque([(x, y)])\n s = set()\n s.add((x, y))\n seen.add((x, y))\n\n while q:\n x, y = q.popleft()\n\n for dx, dy in directions:\n nx, ny = x + dx, y + dy\n \n if not (0 <= nx < M) or not (0 <= ny < N):\n continue\n \n if (nx, ny) in seen or isInfected[nx][ny] == 0:\n continue\n \n if (x, y) in marked[(nx, ny)]:\n continue\n\n seen.add((nx, ny))\n s.add((nx, ny))\n q.append((nx, ny))\n\n return s\n\n\n while True:\n\n groups = []\n seen = set()\n check = True\n \n for i in range(M):\n for j in range(N):\n if not isInfected[i][j]:\n check = False\n continue\n\n if (i, j) in seen:\n continue\n\n s = bfs(i, j)\n groups.append(s)\n \n if check:\n return walls\n \n if not groups:\n return walls\n\n total_walls = []\n \n for g in groups:\n w, t = 0, set()\n for x, y in g:\n\n for dx, dy in directions:\n nx, ny = x + dx, y + dy\n\n if not (0 <= nx < M) or not (0 <= ny < N):\n continue\n\n if (x, y) in marked[(nx, ny)]:\n continue\n\n if (nx, ny) in marked[(x, y)]:\n continue\n\n if isInfected[nx][ny] == 0:\n t.add((nx, ny))\n w += 1\n \n total_walls.append((w, len(t)))\n \n\n i, mx = -1, -1\n\n for index, (w, t) in enumerate(total_walls):\n if t >= mx:\n mx = t\n i = index\n\n if mx == 0:\n return walls\n\n walls += total_walls[i][0]\n\n for x, y in groups[i]:\n for dx, dy in directions:\n nx, ny = x + dx, y + dy\n\n if not (0 <= nx < M) or not (0 <= ny < N):\n continue\n \n if isInfected[nx][ny] == 0:\n marked[(nx, ny)].add((x, y))\n marked[(x, y)].add((nx, ny))\n\n\n\n for index, g in enumerate(groups):\n if index == i:\n continue\n\n for x, y in g:\n for dx, dy in directions:\n nx, ny = x + dx, y + dy\n\n if not (0 <= nx < M) or not (0 <= ny < N):\n continue\n \n if (x, y) in marked[(nx, ny)]:\n continue\n\n isInfected[nx][ny] = 1\n\n\n \n return walls\n \n\n\n \n\n \n\n\n\n \n\n\n\n \n\n\n\n\n\n\n \n``` | 0 | 0 | ['Python3'] | 0 |
contain-virus | Python BFS Clean Approach (beats 100% solutions) | python-bfs-clean-approach-beats-100-solu-lg0z | \n Describe your approach to solving the problem. \n\n# Approach\n\n- Identify Separate Regions: Identify all infected regions and their respective boundaries.\ | codedoctor | NORMAL | 2024-05-18T21:22:05.613168+00:00 | 2024-05-18T21:22:05.613194+00:00 | 4 | false | \n<!-- Describe your approach to solving the problem. -->\n\n# Approach\n\n- Identify Separate Regions: Identify all infected regions and their respective boundaries.\n\n- Prioritize by Threat: Determine which region poses the greatest threat by the number of uninfected cells it can potentially infect.\n\n- Contain the Most Threatening Region: Build walls around the most threatening region to contain the virus there.\n\n- Spread the Virus: Allow the virus to spread from the other regions.\n\n- Repeat: Repeat the above steps until all regions are contained.\n\n\n# Complexity\n- Time complexity: O(m*n)\n\n- Space complexity: O(m*n)\n\n# Code\n```\nclass Solution(object):\n def containVirus(self, isInfected):\n """\n :type isInfected: List[List[int]]\n :rtype: int\n """\n # start with infected cell and map the start of cells to \n def get_regions():\n visited = [[False] * n for _ in range(m)]\n regions = []\n frontiers = []\n walls_needed = []\n \n def bfs(x, y):\n queue = deque([(x, y)])\n visited[x][y] = True\n region = [(x, y)]\n frontier = set()\n walls = 0\n \n while queue:\n cx, cy = queue.popleft()\n for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n nx, ny = cx + dx, cy + dy\n if 0 <= nx < m and 0 <= ny < n:\n if not visited[nx][ny]:\n if isInfected[nx][ny] == 1:\n visited[nx][ny] = True\n queue.append((nx, ny))\n region.append((nx, ny))\n elif isInfected[nx][ny] == 0:\n frontier.add((nx, ny))\n walls += 1\n return region, frontier, walls\n \n for i in range(m):\n for j in range(n):\n if isInfected[i][j] == 1 and not visited[i][j]:\n region, frontier, walls = bfs(i, j)\n if region:\n regions.append(region)\n frontiers.append(frontier)\n walls_needed.append(walls)\n \n return regions, frontiers, walls_needed\n \n m, n = len(isInfected), len(isInfected[0])\n total_walls = 0\n \n while True:\n regions, frontiers, walls_needed = get_regions()\n if not regions:\n break\n \n # Find the region with the maximum threat\n max_threat_index = max(range(len(frontiers)), key=lambda i: len(frontiers[i]))\n total_walls += walls_needed[max_threat_index]\n \n # Contain the most threatening region\n for x, y in regions[max_threat_index]:\n isInfected[x][y] = -1\n \n # Spread the virus from other regions\n for i in range(len(regions)):\n if i == max_threat_index:\n continue\n for x, y in frontiers[i]:\n isInfected[x][y] = 1\n \n return total_walls\n``` | 0 | 0 | ['Python'] | 0 |
contain-virus | BEST C++ SOLUTION WITH 41MS OF RUNTIME ! | best-c-solution-with-41ms-of-runtime-by-fag4c | \n# Code\n\nstruct Region {\n // Given m = the number of rows and n = the number of columns, (x, y) will be\n // hashed as x * n + y.\n unordered_set<int> in | rishabnotfound | NORMAL | 2024-04-23T06:55:59.744725+00:00 | 2024-04-23T06:55:59.744748+00:00 | 38 | false | \n# Code\n```\nstruct Region {\n // Given m = the number of rows and n = the number of columns, (x, y) will be\n // hashed as x * n + y.\n unordered_set<int> infected;\n unordered_set<int> noninfected;\n int wallsRequired = 0;\n};\n\nclass Solution {\n public:\n int containVirus(vector<vector<int>>& isInfected) {\n const int m = isInfected.size();\n const int n = isInfected[0].size();\n int ans = 0;\n\n while (true) {\n vector<Region> regions;\n vector<vector<bool>> seen(m, vector<bool>(n));\n\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (isInfected[i][j] == 1 && !seen[i][j]) {\n Region region;\n // Use DFS to find all the regions (1s).\n dfs(isInfected, i, j, region, seen);\n if (!region.noninfected.empty())\n regions.push_back(region);\n }\n\n if (regions.empty())\n break; // No region causes further infection.\n\n // Regions that infect the most neighbors will be sorted to the back of\n // the array.\n ranges::sort(regions, [](const Region& a, const Region& b) {\n return a.noninfected.size() < b.noninfected.size();\n });\n\n // Build walls around the region that infects the most neighbors.\n Region mostInfectedRegion = regions.back();\n regions.pop_back();\n ans += mostInfectedRegion.wallsRequired;\n\n for (const int neighbor : mostInfectedRegion.infected) {\n const int i = neighbor / n;\n const int j = neighbor % n;\n // The isInfected is now contained and won\'t be infected anymore.\n isInfected[i][j] = 2;\n }\n\n // For remaining regions, infect their neighbors.\n for (const Region& region : regions)\n for (const int neighbor : region.noninfected) {\n const int i = neighbor / n;\n const int j = neighbor % n;\n isInfected[i][j] = 1;\n }\n }\n\n return ans;\n }\n\n private:\n void dfs(const vector<vector<int>>& isInfected, int i, int j, Region& region,\n vector<vector<bool>>& seen) {\n if (i < 0 || i == isInfected.size() || j < 0 || j == isInfected[0].size())\n return;\n if (seen[i][j] || isInfected[i][j] == 2)\n return;\n if (isInfected[i][j] == 0) {\n region.noninfected.insert(i * isInfected[0].size() + j);\n ++region.wallsRequired;\n return;\n }\n\n // isInfected[i][j] == 1\n seen[i][j] = true;\n region.infected.insert(i * isInfected[0].size() + j);\n\n dfs(isInfected, i + 1, j, region, seen);\n dfs(isInfected, i - 1, j, region, seen);\n dfs(isInfected, i, j + 1, region, seen);\n dfs(isInfected, i, j - 1, region, seen);\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
contain-virus | [CPP] Clean Code for Interviews | cpp-clean-code-for-interviews-by-tr1ten-ujof | \n\n# Code\n\n\n\nstruct Region {\n unordered_set<int> inf;\n unordered_set<int> non_inf;\n int walls;\n};\nbool operator<(const Region &r,const Region | tr1ten | NORMAL | 2024-04-21T06:16:42.301856+00:00 | 2024-04-21T06:16:42.301893+00:00 | 54 | false | \n\n# Code\n```\n\n\nstruct Region {\n unordered_set<int> inf;\n unordered_set<int> non_inf;\n int walls;\n};\nbool operator<(const Region &r,const Region &b){\n return r.non_inf.size() < b.non_inf.size();\n}\n\nclass Solution {\npublic:\n vector<Region> regions; \n vector<vector<int>> mat;\n vector<vector<bool>> seen;\n int n,m;\n int comp(int i,int j) {\n return i*m + j;\n }\n pair<int,int> dec(int mask) {\n return {mask/m, mask%m};\n }\n int containVirus(vector<vector<int>>& isInfected) {\n n = isInfected.size();\n m = isInfected[0].size();\n mat = isInfected;\n int ans = 0;\n while(1) {\n seen.clear();\n seen.resize(n,vector<bool>(m));\n regions.clear();\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(!seen[i][j] && mat[i][j]==1) {\n Region reg{.walls= 0};\n dfs(i,j,reg);\n regions.push_back(reg);\n }\n }\n }\n if(regions.empty()) break;\n sort(regions.begin(),regions.end());\n auto largest = regions.back();\n regions.pop_back();\n ans +=largest.walls;\n for(int mask:largest.inf){\n auto [i,j] = dec(mask);\n mat[i][j] = 2;\n }\n for(auto left_r: regions) {\n for(int mask: left_r.non_inf){\n auto [i,j] = dec(mask);\n mat[i][j] = 1;\n }\n }\n }\n return ans;\n }\n void dfs(int i,int j,Region ®) {\n if(i<0 || j<0 || i>=n || j >=m || mat[i][j]==2) return;\n \n if(mat[i][j]==0) {\n reg.non_inf.insert(comp(i,j));\n reg.walls++;\n return;\n };\n if(seen[i][j]) return;\n seen[i][j] =1;\n reg.inf.insert(comp(i,j));\n \n dfs(i+1,j,reg);\n dfs(i,j+1,reg);\n dfs(i-1,j,reg);\n dfs(i,j-1,reg);\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
contain-virus | straightforward solution w/ detailed comments | straightforward-solution-w-detailed-comm-cboc | Code\n\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n if all(cell == 0 for row in isInfected for cell in row): retur | jyscao | NORMAL | 2024-04-14T20:26:39.806370+00:00 | 2024-04-14T20:39:27.885830+00:00 | 14 | false | # Code\n```\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n if all(cell == 0 for row in isInfected for cell in row): return 0\n\n m, n = len(isInfected), len(isInfected[0])\n\n # neighbors of a cell are those that are 4-directionally adjacent w/o going out of bounds\n def get_cell_neighbors(y, x):\n return set((i, j) for (i, j) in ((y - 1, x), (y + 1, x), (y, x - 1), (y, x + 1),)\n if 0 <= i < m and 0 <= j < n)\n \n quarantined_cells = set() # set tracking positions of all cells that have been quarantined\n \n # compute list of 2-tuples containing info on disjoint infected regions; each 2-tuple holds\n # the positions of a continuous infected region & positions on its uninfected boundary cells\n def get_infected_regions():\n regions, visited = [], set()\n\n # stack holding all infected cells; used to perform DFS to find disjoint infected regions\n inf_stk = [(i, j) for i, row in enumerate(isInfected) for j, cell in enumerate(row)\n if isInfected[i][j] and (i, j) not in quarantined_cells]\n while inf_stk:\n pos = inf_stk.pop()\n if pos in visited: continue\n\n # remove neighbors that have already been quarantined to get non-infected neighbors\n unknown_nbrs = get_cell_neighbors(*pos).difference(quarantined_cells)\n\n # if the current infected cell is part of the running not-known-to-be-infected boundary\n # of the infected region currently being searched for, add it to the infected region,\n # and add its own non-infected neighbors to the running not-known-to-be-infected boundary\n if regions and pos in regions[-1][1]:\n regions[-1][0].add(pos)\n regions[-1][1].update(unknown_nbrs)\n \n # otherwise, the current infected cell must be a part of a new disjoint infection region\n else:\n regions.append(({pos}, unknown_nbrs))\n\n # push reachable neighbors that are also infected onto the infection-stack for DFS\n for i, j in unknown_nbrs:\n if isInfected[i][j] == 1: inf_stk.append((i, j))\n \n visited.add(pos)\n \n # remove the infected cells themselves from their boundaries to get set of uninfected cells\n for inf_reg, inf_bound in regions: inf_bound.difference_update(inf_reg)\n \n # sort the list of 2-tups in descending order by size of each region\'s uninfected-neighbors\n return sorted(regions, key=lambda reg_tup: len(reg_tup[1]), reverse=True)\n\n # the perimeter required to wall-in each infected region is equal to the sum \n # of the count of infected cells that border each uninfected neighboring cell\n def calc_wall_perimeter(inf_reg, inf_bound):\n return sum(len(get_cell_neighbors(i, j).intersection(inf_reg)) for (i, j) in inf_bound)\n\n res = 0\n while True:\n # we call `get_infected_regions` at each iteration to avoid having to manually\n # merge previously disjoint regions that have since become continuously infected;\n # this reduces runtime efficiency, but makes the implementation simpler\n (inf_reg_top, inf_bound_top), *remaining_infections = get_infected_regions()\n\n # add perimeter of walls needed to quarantine the most-infected region to result\n res += calc_wall_perimeter(inf_reg_top, inf_bound_top)\n\n # add all cells of the current iteration\'s most infectious region to the quarantined set\n for cell in inf_reg_top: quarantined_cells.add(cell)\n\n # exit when either all infected regions are quarantined, or all cells are infected \n if not remaining_infections: break\n \n # infect all non-infected boundary cells of the remainining unquarantined regions\n for _, inf_bound in remaining_infections:\n for i, j in inf_bound: isInfected[i][j] = 1\n \n return res\n```\n\n# Complexity\n- Time complexity: $$O(k*mn)$$, where $k$ is the number of disjoint infected regions\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(mn)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> | 0 | 0 | ['Depth-First Search', 'Graph', 'Matrix', 'Python3'] | 0 |
contain-virus | DFS | dfs-by-kaicool9789-sc2s | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | kaicool9789 | NORMAL | 2024-04-13T08:00:37.727676+00:00 | 2024-04-13T08:00:37.727706+00:00 | 23 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int containVirus(vector<vector<int>>& a) {\n int m = a.size();\n int n = a[0].size();\n \n vector<vector<int>> dir = {{0,1},{0,-1},{-1,0},{1,0}};\n vector<bool> vs(m*n, false);\n unordered_map<int, vector<int>> vregion; // virus region\n\n /* using set decide priority by size of set without duplocated*/\n unordered_map<int, set<int>> uregion; // uninfected region\n unordered_map<int, int> count; // count for uninfected region\n\n int un_region = 0;\n int virus_region = 0;\n // get all virus ans neighbour region;\n function<void(int)> dfs = [&](int p) {\n vregion[virus_region].push_back(p);\n vs[p] = true;\n for (auto& d : dir) {\n int nx = p/n + d[0];\n int ny = p%n + d[1];\n if (nx < 0 || nx >= m || ny < 0 || ny >= n) continue;\n if (a[nx][ny] == 0) {\n uregion[un_region].insert(nx*n + ny);\n count[un_region]++;\n }\n if (a[nx][ny] == 1 && !vs[nx*n + ny]) dfs(nx*n + ny);\n\n }\n };\n function<void()> calculate_region = [&] () {\n un_region = 0;\n virus_region = 0;\n vregion.clear(); uregion.clear(); count.clear();\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (a[i][j] == 1 && !vs[i*n+j]) {\n dfs(i*n+j);\n un_region++;\n virus_region++;\n }\n }\n }\n };\n int ans= 0;\n while (true) {\n for (int i = 0; i < m*n; i++) vs[i] = false;\n calculate_region();\n if (vregion.size() ==0) break;\n int umax_region = 0;\n int max_num = -1;\n for (auto& m : uregion) {\n int sz = m.second.size();\n if (sz > max_num) {\n max_num = sz;\n umax_region = m.first;\n }\n }\n ans += count[umax_region];\n // change quarantine region to -1;\n for (auto& x : vregion[umax_region]) {\n a[x/n][x%n] = -1;\n }\n // spread virus all other region;\n for (auto&m : uregion) {\n if (m.first == umax_region) continue;\n for (auto& x : m.second) a[x/n][x%n] = 1;\n }\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Depth-First Search', 'C++'] | 0 |
contain-virus | DFS + heap | dfs-heap-by-ynnekuw-kaoj | Intuition\n Describe your first thoughts on how to solve this problem. \n\nPython version of this.\n\n# Code\npython\nfrom heapq import heappush\n\nclass Cluste | ynnekuw | NORMAL | 2024-03-26T07:00:37.136258+00:00 | 2024-03-26T07:00:37.136283+00:00 | 10 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nPython version of [this](https://leetcode.com/problems/contain-virus/solutions/847507/cpp-dfs-solution-explained).\n\n# Code\n```python\nfrom heapq import heappush\n\nclass Cluster:\n def __init__(self):\n self.wall_cnt = 0\n self.cells = set()\n self.neighbors = set()\n \n def __lt__(self, other):\n return len(self.neighbors) >= len(other.neighbors)\n\nclass Solution:\n def dfs(self, i, j, c, seen, isInfected):\n if i >= len(isInfected) or i < 0 or j >= len(isInfected[0]) or j < 0 or (i, j) in seen or isInfected[i][j] == -1:\n return\n if isInfected[i][j] == 0:\n c.wall_cnt += 1\n c.neighbors.add((i, j))\n return\n \n c.cells.add((i, j))\n seen.add((i, j))\n self.dfs(i, j + 1, c, seen, isInfected)\n self.dfs(i, j - 1, c, seen, isInfected)\n self.dfs(i + 1, j, c, seen, isInfected)\n self.dfs(i - 1, j, c, seen, isInfected)\n\n\n\n def containVirus(self, isInfected: List[List[int]]) -> int:\n ans = 0\n m, n = len(isInfected), len(isInfected[0])\n h = []\n\n while True:\n seen = set()\n h = []\n for i in range(m):\n for j in range(n):\n if (i, j) not in seen and isInfected[i][j] == 1:\n c = Cluster()\n self.dfs(i, j, c, seen, isInfected)\n heappush(h, c)\n \n if not h:\n break\n\n c = heappop(h)\n for i, j in c.cells:\n isInfected[i][j] = -1\n \n ans += c.wall_cnt\n\n while h:\n c = heappop(h)\n for i, j in c.neighbors:\n isInfected[i][j] = 1\n \n return ans\n``` | 0 | 0 | ['Python3'] | 0 |
contain-virus | Python - DFS + Dictionary Method | python-dfs-dictionary-method-by-kondrago-5zhf | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | KonDrago | NORMAL | 2024-02-28T05:04:45.400405+00:00 | 2024-02-28T05:08:45.117695+00:00 | 11 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n \n M,N = len(isInfected),len(isInfected[0])\n if M == N == 1:\n return 0\n\n directions = [(1,0),(-1,0),(0,1),(0,-1)]\n\n def inbound(pt):\n return M > pt[0] >= 0 <= pt[1] < N\n\n virusLoc = set()\n for i in range(M):\n for j in range(N):\n if isInfected[i][j]:\n virusLoc.add((i,j))\n\n #DFS walk through virus regions\n def walker(pt, regionId):\n (r,c) = pt\n virusRegion[regionId].add((r,c))\n virusLoc.remove((r,c))\n neighbors = [(r+d[0],c+d[1]) for d in directions]\n neighbors = [n for n in neighbors if inbound(n)]\n for (x,y) in neighbors:\n if (x,y) in virusLoc:\n walker((x,y), regionId)\n return\n\n #populate virusRegion dictionary\n virusRegion = defaultdict(set)\n id = 1\n while virusLoc:\n virusLoc.add(seed := virusLoc.pop())\n walker(seed,id)\n id += 1\n \n #wall off specific virus cluster by flipping sign of id\n def wallOff(id):\n virusRegion[-id] = virusRegion.pop(id)\n\n #helper function to display remaining active regions\n def printVirusRegion():\n for id in virusRegion.keys():\n if id > 0:\n print("ID:", id, virusRegion[id])\n\n #printVirusRegion()\n\n #populate each virus region\n def spreadVirus(id):\n allVirus = set(chain.from_iterable(virusRegion.values()))\n VR = set()\n\n for (r,c) in virusRegion[id].copy():\n VR.add((r,c))\n neighbors = [(r+d[0],c+d[1]) for d in directions]\n neighbors = [n for n in neighbors if inbound(n)]\n for n in neighbors:\n if not n in allVirus:\n VR.add(n)\n return VR\n\n\n def findRegionToWallOff():\n regionToWallOff = 0\n maxSpread = -1\n for id in [id for id in virusRegion.keys() if id > 0]:\n deltaSpread = len(spreadVirus(id)) - len(virusRegion[id])\n if deltaSpread > maxSpread:\n maxSpread = deltaSpread\n regionToWallOff = id\n\n return regionToWallOff\n \n #combine regions - critical (can be further optimized)\n def combineRegions():\n regions = [id for id in list(virusRegion.keys()) if id>0]\n\n regionsMerged = 0\n for id0 in regions:\n v0 = virusRegion[id0]\n n0 = [[(r+d[0],c+d[1]) for d in directions] for (r,c) in v0]\n n0 = set(chain.from_iterable(n0))\n for id1 in regions:\n if id0 != id1:\n v1 = virusRegion[id1]\n if n0.intersection(v1):\n print("Merging regions:", id0, id1)\n regionsMerged += 1\n virusRegion[id0] = virusRegion[id0].union(virusRegion.pop(id1))\n\n for id in list(virusRegion.keys()):\n if not virusRegion[id]:\n print("Deleting region:", id)\n del virusRegion[id]\n\n return regionsMerged\n\n #count number of walls (negative regions only!)\n def countWalls(id):\n allVirus = set(chain.from_iterable(virusRegion.values()))\n ct = 0\n for (r,c) in virusRegion[id]:\n neighbors = [(r+d[0],c+d[1]) for d in directions]\n neighbors = [n for n in neighbors if inbound(n)]\n for n in neighbors:\n if not n in allVirus:\n ct+=1\n return ct\n\n totalWalls = 0\n while max(virusRegion.keys()) > 0:\n\n #count number of walls used for this wall-off\n wallOffId = findRegionToWallOff()\n wallOff(wallOffId)\n wallsUsed = countWalls(-wallOffId)\n totalWalls += wallsUsed\n \n #spread "simultaneously", not iterative.\n nextSpread = defaultdict(set)\n for id in [id for id in virusRegion.keys() if id > 0]:\n nextSpread[id] = spreadVirus(id) \n for id in [id for id in virusRegion.keys() if id > 0]: \n virusRegion[id] = nextSpread[id]\n\n while combineRegions():\n 0 #do nothing, just needs to combine\n \n print("Quarantine Complete")\n\n return totalWalls\n``` | 0 | 0 | ['Python3'] | 0 |
contain-virus | ✅ Easy BFS solution | Python | easy-bfs-solution-python-by-anujmah-ntzt | Code\n\nfrom collections import deque\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n rows = len(isInfected)\n | anujmah | NORMAL | 2024-02-24T20:16:43.344195+00:00 | 2024-02-24T20:16:43.344227+00:00 | 43 | false | # Code\n```\nfrom collections import deque\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n rows = len(isInfected)\n col = len(isInfected[0])\n\n # get all the contaminated cells present using BFS\n def getContaminatedArea():\n infectedAreas = []\n toBeInfectedAreas = []\n walls = []\n visited = [[False] * col for _ in range(rows)]\n\n for r in range(rows):\n for c in range(col):\n infectedArea = []\n toBeInfectedArea = set()\n wall = 0\n queue = deque()\n if isInfected[r][c] == 1 and not visited[r][c]:\n queue.append((r,c))\n infectedArea = [(r,c)]\n visited[r][c] = True\n while queue:\n popr, popc = queue.popleft()\n moves = [[1,0], [-1,0], [0,1], [0,-1]]\n for move in moves:\n if rows > popr + move[0] >= 0 and col > popc + move[1] >= 0:\n if isInfected[popr + move[0]][popc + move[1]] == 1 and not visited[popr + move[0]][popc + move[1]]:\n queue.append((popr + move[0], popc + move[1]))\n visited[popr + move[0]][popc + move[1]] = True\n infectedArea.append((popr + move[0], popc + move[1]))\n elif isInfected[popr + move[0]][popc + move[1]] == 0:\n toBeInfectedArea.add((popr + move[0], popc + move[1]))\n wall += 1\n infectedAreas.append(infectedArea)\n toBeInfectedAreas.append(toBeInfectedArea)\n walls.append(wall)\n return infectedAreas, toBeInfectedAreas, walls\n \n ## Spread the virus after each successful iteration of building walls\n def spreadVirus(spreadingAreas):\n for area in spreadingAreas:\n for cell in area:\n isInfected[cell[0]][cell[1]] = 1\n\n\n def no_of_elements_in_2d_list(list_2d):\n return sum(len(li) for li in list_2d)\n\n\n infectedAreas, toBeInfectedAreas, walls = getContaminatedArea()\n wallCount = 0\n while infectedAreas:\n mostInfectedIndex = 0\n\n totalInfectedCells = 0\n for i in range(len(infectedAreas)):\n totalInfectedCells += len(infectedAreas[i])\n\n if totalInfectedCells == rows * col:\n return wallCount\n\n for i in range(len(toBeInfectedAreas)):\n if len(toBeInfectedAreas[i]) > len(toBeInfectedAreas[mostInfectedIndex]):\n mostInfectedIndex = i\n \n for index in infectedAreas[mostInfectedIndex]:\n isInfected[index[0]][index[1]] = -1\n \n wallCount += walls[mostInfectedIndex]\n \n spreadVirus(toBeInfectedAreas[:mostInfectedIndex] + toBeInfectedAreas[mostInfectedIndex + 1:])\n\n infectedAreas, toBeInfectedAreas, walls = getContaminatedArea()\n \n return wallCount\n\n``` | 0 | 0 | ['Array', 'Breadth-First Search', 'Matrix', 'Simulation', 'Python3'] | 0 |
contain-virus | O(nm α(nm)) ≈ O(nm) || Python Solution || Union-Find | onm-anm-onm-python-solution-union-find-b-pwqb | \nclass DisjointSet:\n def __init__(self, iterable):\n self.parent = {}\n self.rank = {}\n\n for x in iterable:\n self.make_s | tom7em | NORMAL | 2024-02-19T11:11:35.832766+00:00 | 2024-02-19T11:11:35.832794+00:00 | 13 | false | ```\nclass DisjointSet:\n def __init__(self, iterable):\n self.parent = {}\n self.rank = {}\n\n for x in iterable:\n self.make_set(x)\n\n def __contains__(self, x):\n return x in self.parent\n\n def make_set(self, x):\n self.parent[x] = x\n self.rank[x] = 0\n\n def find(self, x):\n while self.parent[x] != x:\n self.parent[x] = self.parent[self.parent[x]]\n x = self.parent[x]\n return x\n\n def union(self, x, y):\n x = self.find(x)\n y = self.find(y)\n\n if x == y:\n return x\n\n if self.rank[x] < self.rank[y]:\n x, y = y, x\n\n self.parent[y] = x\n if self.rank[x] == self.rank[y]:\n self.rank[x] += 1\n\n\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n n, m = len(isInfected), len(isInfected[0])\n\n def neighbors(x):\n i, j = x\n for i_d, j_d in ((0, 1), (0, -1), (1, 0), (-1, 0)):\n ii = i + i_d\n jj = j + j_d\n if 0 <= ii < n and 0 <= jj < m:\n yield (ii, jj)\n\n isolated = set()\n last_infected = set(\n (i, j) for i in range(n) for j in range(m) if isInfected[i][j]\n )\n ds = DisjointSet(last_infected)\n res = 0\n\n while last_infected:\n for x in last_infected:\n for y in neighbors(x):\n if y in ds and ds.find(y) not in isolated:\n ds.union(x, y)\n\n candidates = defaultdict(list)\n for x in last_infected:\n root = ds.find(x)\n for y in neighbors(x):\n if y not in ds:\n candidates[root].append(y)\n\n if not candidates:\n break\n\n key = lambda root: len(set(candidates[root]))\n max_root = max(candidates.keys(), key=key)\n res += len(candidates[max_root])\n isolated.add(max_root)\n del candidates[max_root]\n\n last_infected = set()\n for root, cells in candidates.items():\n for x in cells:\n if x not in ds:\n last_infected.add(x)\n ds.make_set(x)\n ds.union(root, x)\n\n return res\n\n``` | 0 | 0 | ['Python3'] | 0 |
contain-virus | JS || Solution by Bharadwaj | js-solution-by-bharadwaj-by-manu-bharadw-5lqt | Code\n\nclass CircularQueue {\n\n constructor(capacity) {\n\n this._capacity = capacity;\n\n this._size = 0;\n\n this._bottom = 0;\n\n | Manu-Bharadwaj-BN | NORMAL | 2024-02-07T06:06:04.667019+00:00 | 2024-02-07T06:06:04.667037+00:00 | 13 | false | # Code\n```\nclass CircularQueue {\n\n constructor(capacity) {\n\n this._capacity = capacity;\n\n this._size = 0;\n\n this._bottom = 0;\n\n this._data = Array(capacity).fill(undefined);\n }\n\n _getCircularIndex(index) {\n const result = index % this._capacity;\n if (result < 0) result += this._capacity;\n return result;\n }\n\n get capacity() {\n return this._capacity;\n }\n\n get size() {\n return this._size;\n }\n\n get nextItem() {\n return this._size ? this._data[this._bottom] : undefined;\n }\n\n get lastItem() {\n return this._size\n ? this._data[this._getCircularIndex(this._bottom + this._size - 1)]\n : undefined;\n }\n\n enqueue(...items) {\n if (this._size + items.length > this._capacity)\n throw new Error("Queue capacity exceeded.");\n\n let queueIndex = (this._bottom + this._size) % this._capacity;\n this._size += items.length;\n for (let i = 0; i < items.length; i++) {\n this._data[queueIndex] = items[i];\n queueIndex = (queueIndex + 1) % this._capacity;\n }\n }\n\n dequeue() {\n if (!this._size) return undefined;\n\n let result = this._data[this._bottom];\n this._bottom = (this._bottom + 1) % this._capacity;\n this._size--;\n\n return result;\n }\n\n clear() {\n this._size = 0;\n }\n}\n\nlet qr = new CircularQueue(2500);\nlet qc = new CircularQueue(2500);\n\nlet threats = [];\nlet fences = [];\nfunction initLabel(x) {\n while (x >= threats.length) {\n threats.push(0);\n fences.push(0);\n }\n threats[x] = 0;\n fences[x] = 0;\n}\n\nlet DIR_R = [0, 0, 1, -1];\nlet DIR_C = [1, -1, 0, 0];\n\nvar containVirus = function (isInfected) {\n let n = isInfected[0].length;\n let m = isInfected.length;\n let label = 0;\n let res = 0;\n\n function bfs(ir, ic, label) {\n qr.enqueue(ir);\n qc.enqueue(ic);\n let labelState = (label << 3) | 2;\n isInfected[ir][ic] = labelState;\n initLabel(label);\n\n while (qr.size) {\n let r = qr.dequeue();\n let c = qc.dequeue();\n\n for (let i = 0; i < 4; i++) {\n let rr = r + DIR_R[i];\n let cc = c + DIR_C[i];\n let state = isInfected[rr]?.[cc];\n if (state == undefined) continue;\n\n switch (state & 7) {\n case 0: {\n isInfected[rr][cc] = (label << 3) | 3;\n fences[label]++;\n threats[label]++;\n break;\n }\n case 1: {\n qr.enqueue(rr);\n qc.enqueue(cc);\n isInfected[rr][cc] = labelState;\n break;\n }\n case 3: {\n fences[label]++;\n if ((state >> 3) != label) {\n threats[label]++;\n isInfected[rr][cc] = (label << 3) | 3;\n }\n break;\n }\n }\n }\n }\n }\n\n function isStillThreaten(r, c, lockedLabel) {\n for (let i = 0; i < 4; i++) {\n let rr = r + DIR_R[i];\n let cc = c + DIR_C[i];\n let state = isInfected[rr]?.[cc];\n if ((state & 7) == 2 && (state >> 3) != lockedLabel) return true;\n }\n }\n\n while (true) {\n label = 0;\n let lockedLabel = 0;\n\n for (let r = 0; r < m; r++) {\n for (let c = 0; c < n; c++) {\n if (isInfected[r][c] == 1) {\n bfs(r, c, label);\n if (threats[label] > threats[lockedLabel]) lockedLabel = label;\n label++;\n }\n }\n }\n\n if (!label) return res;\n\n res += fences[lockedLabel];\n\n for (let r = 0; r < m; r++) {\n for (let c = 0; c < n; c++) {\n if ((isInfected[r][c] & 7) == 3) {\n if (isStillThreaten(r, c, lockedLabel)) isInfected[r][c] = 1;\n else isInfected[r][c] = 0;\n }\n }\n }\n\n for (let r = 0; r < m; r++) {\n for (let c = 0; c < n; c++) {\n let state = isInfected[r][c];\n if ((state & 7) == 2) {\n if ((state >> 3) == lockedLabel) isInfected[r][c] = 4;\n else isInfected[r][c] = 1;\n }\n }\n }\n }\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
contain-virus | TS solution | ts-solution-by-gennadysx-0hlb | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | GennadySX | NORMAL | 2024-01-15T23:25:06.079685+00:00 | 2024-01-15T23:25:06.079703+00:00 | 7 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Region {\n // as need to de-dupe the elements.\n // If N rows and M cols.\n // Total elements = NxM.\n // Given row and col calculate X as: X = row * M + col.\n // Given X calculate row and col as: row = X / M and col = X % M.\n\n // Infected nodes represented by 1.\n infected = new Set<number>();\n\n // Uninfected neighbors represented by 0 are the ones this region can infect if not contained.\n uninfectedNeighbors = new Set<number>();\n\n // Number of walls required to contain all the infected nodes (1s) in this region.\n // Note that two infected 1s can infect the same 0, so in this case we need two walls to save one 0 from two 1s.\n wallsRequired = 0;\n}\n\nfunction containVirus(grid: number[][]): number {\n if (grid == null || grid.length == 0) {\n return 0;\n }\n\n const rows = grid.length;\n const cols = grid[0].length;\n\n let result = 0;\n\n while (true) {\n const regions: Region[] = [];\n\n // Find all the regions using DFS (or can also use BFS).\n const visited = new Array(rows).fill(false).map(() => new Array(cols).fill(false));\n for (let row = 0; row < rows; row++) {\n for (let col = 0; col < cols; col++) {\n if (grid[row][col] == 1 && !visited[row][col]) {\n const region = new Region();\n dfs(grid, row, col, visited, region);\n\n // Add region to list of regions only if it can cause infection.\n if (region.uninfectedNeighbors.size > 0) {\n regions.push(region);\n }\n }\n }\n }\n\n // No more regions that can cause further infection, we are done.\n if (regions.length == 0) {\n break;\n }\n\n // Sort the regions. Region which can infected most neighbors first.\n regions.sort((o1, o2) => {\n return o2.uninfectedNeighbors.size - o1.uninfectedNeighbors.size;\n });\n\n // Build wall around region which can infect most neighbors.\n const regionThatCauseMostInfection = regions.shift();\n result += regionThatCauseMostInfection.wallsRequired;\n\n for (const neighbor of regionThatCauseMostInfection.infected) {\n const row = Math.floor(neighbor / cols);\n const col = neighbor % cols;\n\n // Choosing 2 as to denote that this cell is now contained\n // and will not cause any more infection.\n grid[row][col] = 2;\n }\n\n // For remaining regions, expand (neighbors are now infected).\n for (const region of regions) {\n for (const neighbor of region.uninfectedNeighbors) {\n const row = Math.floor(neighbor / cols);\n const col = neighbor % cols;\n grid[row][col] = 1;\n }\n }\n }\n\n return result;\n}\n\n\nfunction dfs(grid: number[][], row: number, col: number, visited: boolean[][], region: Region) {\n const rows = grid.length;\n const cols = grid[0].length;\n\n if (row < 0 || row >= rows || col < 0 || col >= cols || grid[row][col] == 2) {\n return;\n }\n\n if (grid[row][col] == 1) {\n // 1 is already infected.\n // Add to the list, since we are using Set it will be deduped if added multiple times.\n region.infected.add(row * cols + col);\n\n // If already visited, return as we do not want to go into infinite recursion.\n if (visited[row][col]) {\n return;\n }\n }\n\n visited[row][col] = true;\n\n if (grid[row][col] == 0) {\n // If 0 it is uninfected neighbor, we need a wall.\n // Remeber we can reach this 0 multiple times from different infected neighbors i.e. 1s,\n // and this will account for numbers of walls need to be built around this 0.\n region.wallsRequired++;\n\n // Add to uninfected list, it will be de-duped as we use Set.\n region.uninfectedNeighbors.add(row * cols + col);\n return;\n }\n\n // Visit neighbors.\n dfs(grid, row + 1, col, visited, region);\n dfs(grid, row - 1, col, visited, region);\n dfs(grid, row, col + 1, visited, region);\n dfs(grid, row, col - 1, visited, region);\n}\n``` | 0 | 0 | ['TypeScript'] | 0 |
contain-virus | 749. Contain Virus.cpp | 749-contain-viruscpp-by-202021ganesh-8bjo | Code\n\nclass Solution {\npublic:\n int containVirus(vector<vector<int>>& grid) {\n int ans = 0;\n while (true) {\n int walls = mode | 202021ganesh | NORMAL | 2024-01-10T16:25:51.565552+00:00 | 2024-01-10T16:25:51.565594+00:00 | 8 | false | **Code**\n```\nclass Solution {\npublic:\n int containVirus(vector<vector<int>>& grid) {\n int ans = 0;\n while (true) {\n int walls = model(grid);\n if (walls == 0) break;\n ans += walls;\n }\n return ans;\n }\nprivate:\n int model(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size(), N = 100;\n vector<unordered_set<int>> virus, toInfect;\n vector<vector<int>> visited(m, vector<int>(n, 0));\n vector<int> walls;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1 && visited[i][j] == 0) {\n virus.push_back(unordered_set<int>());\n toInfect.push_back(unordered_set<int>());\n walls.push_back(0);\n dfs(grid, visited, virus.back(), toInfect.back(), walls.back(), i, j);\n }\n }\n }\n int maxArea = 0, idx = -1;\n for (int i = 0; i < toInfect.size(); i++) {\n if (toInfect[i].size() > maxArea) {\n maxArea = toInfect[i].size();\n idx = i;\n }\n }\n if (idx == -1) return 0;\n for (int i = 0; i < toInfect.size(); i++) {\n if (i != idx) {\n for (int key : toInfect[i]) \n grid[key/N][key%N] = 1;\n }\n else {\n for (int key: virus[i]) \n grid[key/N][key%N] = -1;\n }\n }\n return walls[idx];\n }\nprivate:\n void dfs(vector<vector<int>>& grid, vector<vector<int>>& visited, unordered_set<int>& virus, unordered_set<int>& toInfect, int& wall, int row, int col) {\n int m = grid.size(), n = grid[0].size(), N = 100;\n if (row < 0 || row >= m || col < 0 || col >= n || visited[row][col] == 1) return;\n if (grid[row][col] == 1) {\n visited[row][col] = 1;\n virus.insert(row*N + col);\n vector<int> dir = {0, -1, 0, 1, 0};\n for (int i = 0; i < 4; i++)\n dfs(grid, visited, virus, toInfect, wall, row+dir[i], col+dir[i+1]);\n }\n else if (grid[row][col] == 0) {\n wall++;\n toInfect.insert(row*N + col);\n }\n }\n};\n``` | 0 | 0 | ['C'] | 0 |
contain-virus | python | python-by-susmita2004-ng16 | \n\n# Code\n\nclass Solution:\n def containVirus(self, mat: List[List[int]]) -> int:\n m, n = len(mat), len(mat[0])\n DIRECTIONS = [(-1, 0), (1 | susmita2004 | NORMAL | 2023-12-30T16:37:48.492017+00:00 | 2023-12-30T16:37:48.492044+00:00 | 6 | false | \n\n# Code\n```\nclass Solution:\n def containVirus(self, mat: List[List[int]]) -> int:\n m, n = len(mat), len(mat[0])\n DIRECTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n \n def dfs(i, j, visited):\n if not (0 <= i < m and 0 <= j < n) or (i, j) in visited:\n return set(), 0\n if mat[i][j] == 2:\n return set(), 0\n elif mat[i][j] == 0:\n return {(i, j)}, 1\n \n visited.add((i, j))\n infected, walls = set(), 0\n for dx, dy in DIRECTIONS:\n ni, nj = i + dx, j + dy\n next_infected, next_walls = dfs(ni, nj, visited)\n infected |= next_infected\n walls += next_walls\n return infected, walls\n \n def quarantine(i, j):\n if 0 <= i < m and 0 <= j < n and mat[i][j] == 1:\n mat[i][j] = 2\n for dx, dy in DIRECTIONS:\n quarantine(i + dx, j + dy)\n \n ans = 0\n while True:\n visited, regions = set(), []\n for i in range(m):\n for j in range(n):\n if mat[i][j] == 1 and (i, j) not in visited:\n infected, walls = dfs(i, j, visited)\n if infected:\n regions.append((infected, walls, (i, j)))\n \n if not regions:\n break\n \n regions.sort(key=lambda x: (-len(x[0]), x[1]))\n max_infected, max_walls, start = regions[0]\n ans += max_walls\n quarantine(*start)\n \n for region in regions[1:]:\n for i, j in region[0]:\n mat[i][j] = 1\n \n return ans\n``` | 0 | 0 | ['Python3'] | 0 |
contain-virus | Simulation using easy to follow code | simulation-using-easy-to-follow-code-by-rd6oc | Intuition\nSimulate the virus containment and spreading in a clear\nand easy to understand way. \n\n# Approach\nSimulates each tick of the containment and infec | grangej | NORMAL | 2023-12-04T22:34:50.067469+00:00 | 2023-12-04T22:34:50.067497+00:00 | 12 | false | # Intuition\nSimulate the virus containment and spreading in a clear\nand easy to understand way. \n\n# Approach\nSimulates each tick of the containment and infection, while tracking the virus that are not contained.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport Foundation\n\n\nclass Solution { // O(m*n)^2 + O(m*n) space\n \n enum CellStructure: Equatable {\n case normal\n case infected\n case infectedWithID(UUID)\n case contained\n \n init(_ integerValue: Int) {\n self = (integerValue == 0) ? .normal : .infected\n }\n \n var isInfected: Bool {\n switch self {\n case .infected, .infectedWithID: return true\n default: return false\n }\n }\n \n var infectionId: UUID? {\n switch self {\n case .infectedWithID(let id): return id\n default: return nil\n }\n }\n }\n \n struct Point: Equatable, Hashable {\n let x: Int\n let y: Int\n \n init(_ x: Int, _ y: Int) {\n self.x = x\n self.y = y\n }\n \n init(row: Int, column: Int) {\n self.x = column\n self.y = row\n }\n \n var up: Point { Point(x, y - 1) }\n var down: Point { Point(x, y + 1) }\n var left: Point { Point(x - 1, y) }\n var right: Point { Point(x + 1, y) }\n }\n \n struct Infection: Equatable, Hashable, Comparable {\n let id: UUID = UUID()\n var cells: Set<Point>\n var adjacentCells: Set<Point>\n \n static func <(lhs: Infection, rhs: Infection) -> Bool {\n return lhs.adjacentCells.count < rhs.adjacentCells.count\n }\n }\n \n var body: [[CellStructure]] = [[CellStructure]]()\n var walls: [Point] = []\n var infections: [UUID: Infection] = [:]\n \n func containVirus(_ isInfected: [[Int]]) -> Int { // O(n*m)\n \n self.body = isInfected.map { row in row.map { CellStructure($0) } }\n \n infections = self.catalogInfections()\n \n while !infections.isEmpty {\n \n var sortedInfections = Array(infections.values).sorted(by: <) // O(k * log(k))\n \n if let infection = sortedInfections.popLast() {\n self.infections[infection.id] = nil\n var inspectedInfection = Set<Point>()\n containInfection(infection.cells.first!, inspectedInfection: &inspectedInfection)\n }\n \n var inspectedBody = Set<Point>()\n \n while var infection = sortedInfections.popLast() {\n spreadInfection(&infection, inspectedBody: &inspectedBody)\n if infection.cells.count > 0 {\n infections[infection.id] = infection\n } else {\n infections[infection.id] = nil\n }\n }\n }\n \n return walls.count\n }\n \n private func catalogInfections() -> [UUID: Infection] { // O(m*n)\n \n let rows = body.count\n let columns = body[0].count\n \n var inspectedBody: Set<Point> = []\n \n var infections: [UUID: Infection] = [:]\n \n for row in 0..<rows {\n for column in 0..<columns {\n let point = Point(row: row, column: column)\n if body.containsPoint(point) && !inspectedBody.contains(point) && body.containsSpreadableInfection(atPoint: point) {\n var infection = Infection(cells: [], adjacentCells: [])\n findInfectionsAtPoint(point, inspectedBody: &inspectedBody, infection: &infection)\n infections[infection.id] = infection\n }\n }\n }\n \n return infections\n }\n \n private func containInfection(_ point: Point, inspectedInfection: inout Set<Point>) { // O(m*n)\n \n guard body.containsPoint(point), !inspectedInfection.contains(point), body.containsSpreadableInfection(atPoint: point) else { return }\n \n inspectedInfection.insert(point)\n body[point] = .contained\n let adjacentCells = adjacentCells(point)\n for adjacentCell in adjacentCells {\n walls.append(adjacentCell)\n }\n \n containInfection(point.left, inspectedInfection: &inspectedInfection)\n containInfection(point.right, inspectedInfection: &inspectedInfection)\n containInfection(point.up, inspectedInfection: &inspectedInfection)\n containInfection(point.down, inspectedInfection: &inspectedInfection)\n }\n \n private func spreadInfection(_ infection: inout Infection, inspectedBody: inout Set<Point>) { // O(m*n)\n \n inspectedBody.formUnion(infection.cells)\n \n for cell in infection.adjacentCells {\n \n if body.containsUninfectedCell(atPoint: cell) {\n body[cell] = .infectedWithID(infection.id)\n infection.cells.insert(cell)\n }\n }\n \n infection.adjacentCells.removeAll()\n \n for cell in infection.cells {\n consumeInfection(cell.left, inspectedBody: &inspectedBody, infection: &infection)\n consumeInfection(cell.right, inspectedBody: &inspectedBody, infection: &infection)\n consumeInfection(cell.up, inspectedBody: &inspectedBody, infection: &infection)\n consumeInfection(cell.down, inspectedBody: &inspectedBody, infection: &infection)\n }\n \n for cell in infection.cells {\n infection.adjacentCells.formUnion(self.adjacentCells(cell))\n }\n }\n \n private func consumeInfection(_ point: Point, inspectedBody: inout Set<Point>, infection: inout Infection) {\n \n guard body.containsPoint(point),\n body.containsForeignInfection(atPoint: point, infectionID: infection.id), \n let foreignInfectionID = self.body[point].infectionId,\n let foreignInfection = self.infections[foreignInfectionID] else { return }\n \n defer {\n infections[foreignInfectionID]?.adjacentCells.removeAll()\n infections[foreignInfectionID]?.cells.removeAll()\n }\n \n for cell in foreignInfection.cells {\n body[cell] = .infectedWithID(infection.id)\n infection.cells.insert(cell)\n inspectedBody.insert(cell)\n }\n \n if !inspectedBody.contains(point) {\n for cell in infection.adjacentCells {\n if body.containsUninfectedCell(atPoint: cell) {\n body[cell] = .infectedWithID(infection.id)\n infection.cells.insert(cell)\n }\n }\n }\n }\n\n \n private func findInfectionsAtPoint(_ point: Point, inspectedBody: inout Set<Point>, infection: inout Infection) {\n \n guard body.containsPoint(point), !inspectedBody.contains(point), body.containsSpreadableInfection(atPoint: point) else { return }\n \n inspectedBody.insert(point)\n \n body[point] = .infectedWithID(infection.id)\n infection.cells.insert(point)\n infection.adjacentCells.formUnion(adjacentCells(point))\n \n findInfectionsAtPoint(point.left, inspectedBody: &inspectedBody, infection: &infection)\n findInfectionsAtPoint(point.right, inspectedBody: &inspectedBody, infection: &infection)\n findInfectionsAtPoint(point.up, inspectedBody: &inspectedBody, infection: &infection)\n findInfectionsAtPoint(point.down, inspectedBody: &inspectedBody, infection: &infection)\n }\n \n private func adjacentCells(_ point: Point) -> [Point] {\n \n var adjacentCells: [Point] = []\n if body.containsPoint(point.left), !body.containsInfection(atPoint: point.left) { adjacentCells.append(point.left) }\n if body.containsPoint(point.right), !body.containsInfection(atPoint: point.right) { adjacentCells.append(point.right) }\n if body.containsPoint(point.up), !body.containsInfection(atPoint: point.up) { adjacentCells.append(point.up) }\n if body.containsPoint(point.down), !body.containsInfection(atPoint: point.down) { adjacentCells.append(point.down) }\n\n return adjacentCells\n }\n}\n\ntypealias CellStructure = Solution.CellStructure\n\nprivate extension Array where Element == [CellStructure] {\n \n /// Validates if the point is valid within this 2D Array\n /// - Parameter point: A point to validate in the array\n /// - Returns: `true` if the point is within the 2D Array\n func containsPoint(_ point: Solution.Point) -> Bool {\n guard point.x >= 0, point.y >= 0 else { return false }\n guard point.y < self.count else { return false }\n guard point.x < self[point.y].count else { return false }\n \n return true\n }\n \n /// Validates if a point in the 2D array is infected\n /// - Parameter point: A point to validate in the array\n /// - Returns: `true` if the point is infected or `false` if the point is normal\n func containsInfection(atPoint point: Solution.Point) -> Bool {\n return self[point] != .normal\n }\n \n func containsSpreadableInfection(atPoint point: Solution.Point) -> Bool {\n return self[point].isInfected\n }\n \n func containsUninfectedCell(atPoint point: Solution.Point) -> Bool {\n return self[point] == .normal\n }\n \n func containsForeignInfection(atPoint point: Solution.Point, infectionID: UUID) -> Bool {\n switch self[point] {\n case .infectedWithID(let id): return infectionID != id\n default: return false\n }\n }\n \n subscript(index: Solution.Point) -> CellStructure {\n get {\n assert(containsPoint(index), "Index out of range")\n return self[index.y][index.x]\n }\n set {\n assert(containsPoint(index), "Index out of range")\n self[index.y][index.x] = newValue\n }\n }\n \n var description: String {\n var gridDescription = ""\n \n for row in self {\n for cell in row {\n switch cell {\n case .normal:\n gridDescription += "N " // \'N\' for Normal\n case .infected:\n gridDescription += "I " // \'I\' for Infected\n case .contained:\n gridDescription += "C " // \'C\' for Contained\n case .infectedWithID(_):\n gridDescription += "I " // \'I\' for Infected\n }\n }\n gridDescription += "\\n" // New line at the end of each row\n }\n \n return gridDescription\n }\n}\n\n``` | 0 | 0 | ['Swift'] | 0 |
contain-virus | Using BFS | using-bfs-by-daminibansal1725-pj51 | Code\n\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n m, n = len( | daminibansal1725 | NORMAL | 2023-10-24T07:38:51.803214+00:00 | 2023-10-24T07:38:51.803232+00:00 | 27 | false | # Code\n```\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n m, n = len(isInfected), len(isInfected[0])\n ans = 0\n while True:\n # 1. BFS\n # neighbors stores every to-spread/to-put-wall area. \n # firewalls stores the countings for every area. \n neighbors, firewalls = list(), list()\n for i in range(m):\n for j in range(n):\n if isInfected[i][j] == 1:\n # detect the infected area \n q = deque([(i, j)])\n # index of this area\n idx = len(neighbors) + 1\n # record all cells in this to-spread/to-put-wall area\n neighbor = set()\n # count walls needed\n firewall = 0\n print(i,j,idx)\n # mark as visited\n isInfected[i][j] = -idx\n\n while q:\n x, y = q.popleft()\n for d in range(4):\n # detect around\n nx, ny = x + dirs[d][0], y + dirs[d][1]\n # ensure within the matrix\n if 0 <= nx < m and 0 <= ny < n:\n if isInfected[nx][ny] == 1:\n # update infected area\n q.append((nx, ny))\n # mark as visited\n isInfected[nx][ny] = -idx\n elif isInfected[nx][ny] == 0:\n # update counting and neighbor\n firewall += 1\n neighbor.add((nx, ny))\n\n \n \n # update neighbors and firewalls\n neighbors.append(neighbor)\n firewalls.append(firewall)\n print(neighbors)\n print(firewalls)\n\n # 2. none infected areas\n if not neighbors:\n break\n \n # 3. calculate the largest area:\n idx = 0\n for i in range(1, len(neighbors)):\n if len(neighbors[i]) > len(neighbors[idx]):\n idx = i\n \n # 4. update the ans\n ans += firewalls[idx]\n\n # if only 1 area in total, this is the final answer\n if len(neighbors) == 1:\n # return ans\n break \n \n\n # 5. mark as processed and modify the unprocessed\n print(idx)\n print(isInfected)\n for i in range(m):\n for j in range(n):\n if isInfected[i][j] < 0:\n # unprocess\n if isInfected[i][j] != - (idx + 1):\n isInfected[i][j] = 1\n else:\n isInfected[i][j] = 2\n # 6. mark the spreaded\n for i, neighbor in enumerate(neighbors):\n if i != idx:\n # spread\n for x, y in neighbor:\n isInfected[x][y] = 1\n \n \n\n return ans\n``` | 0 | 0 | ['Python3'] | 0 |
contain-virus | copy paste | copy-paste-by-shivamkhandare03-chvp | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | shivamkhandare03 | NORMAL | 2023-10-23T07:11:30.699409+00:00 | 2023-10-23T07:11:30.699437+00:00 | 29 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n class Region {\n Set<Integer> infected = new HashSet<>();\n Set<Integer> unInfected = new HashSet<>();\n int walls = 0;\n } \n public int containVirus(int[][] isInfected) {\n int ans = 0;\n int re = isInfected.length;\n int ce = isInfected[0].length;\n\n while (true) {\n List<Region> holder = new ArrayList<>();\n boolean[][] v = new boolean[re][ce];\n for (int r = 0; r < re; r++) {\n for (int c = 0; c < ce; c++) {\n if (isInfected[r][c] == 1 && !v[r][c]) {\n Region region = new Region();\n getRegion(isInfected, region, re, ce, v, r, c);\n holder.add(region);\n }\n }\n }\n int indexOfMaxUnInfected = 0;\n int sizeOfMaxUnInfected = 0;\n for (int i = 0; i < holder.size(); i++) {\n Region region = holder.get(i);\n\n if (region.unInfected.size() > sizeOfMaxUnInfected) {\n sizeOfMaxUnInfected = region.unInfected.size();\n indexOfMaxUnInfected = i;\n }\n }\n if (holder.size() == 0) {\n break;\n }\n Set<Integer> maxSet = holder.get(indexOfMaxUnInfected).infected;\n for (int rowCol : maxSet) {\n int r = rowCol / ce;\n int c = rowCol % ce;\n isInfected[r][c] = 2;\n }\n ans += holder.get(indexOfMaxUnInfected).walls;\n for (int i = 0; i < holder.size(); i++) {\n \n if (i == indexOfMaxUnInfected) {\n continue;\n }\n Region region = holder.get(i);\n Set<Integer> unInfected = region.unInfected;\n\n for (int rowCol : unInfected) {\n int r = rowCol / ce;\n int c = rowCol % ce;\n isInfected[r][c] = 1;\n }\n }\n }\n return ans;\n }\n int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n private void getRegion(int[][] isInfected, Region region, int re, int ce, \n boolean[][] v, int r, int c) {\n if (r < 0 || c < 0 || r == re || c == ce || isInfected[r][c] == 2) {\n return;\n }\n if (isInfected[r][c] == 1) {\n if (v[r][c]) {\n return;\n }\n region.infected.add(r * ce + c);\n }\n if (isInfected[r][c] == 0) {\n region.unInfected.add(r * ce + c);\n region.walls++;\n return;\n }\n v[r][c] = true;\n for (int[] dir : dirs) {\n int nr = r + dir[0];\n int nc = c + dir[1];\n getRegion(isInfected, region, re, ce, v, nr, nc);\n }\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
Subsets and Splits