{"id":1280,"date":"2017-12-18T13:46:39","date_gmt":"2017-12-18T21:46:39","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=1280"},"modified":"2018-03-16T00:45:59","modified_gmt":"2018-03-16T07:45:59","slug":"leetcode-749-contain-virus","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/searching\/leetcode-749-contain-virus\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 749. Contain Virus"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 749. Contain Virus - \u5237\u9898\u627e\u5de5\u4f5c EP136\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/lJFy4IojSK0?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p>\u9898\u76ee\u5927\u610f\uff1a\u7ed9\u4f60\u4e00\u4e2a\u683c\u5b50\u5730\u56fe\u4e0a\u9762\u6709\u4e00\u4e9b\u75c5\u6bd2\u75281\u8868\u793a\uff0c\u672a\u53d7\u611f\u67d3\u7684\u683c\u5b50\u75280\u8868\u793a\u3002\u5e26\u6709\u75c5\u6bd2\u7684\u683c\u5b50\u6bcf\u5929\u4f1a\u5411\u56db\u5468\u7684\u683c\u5b50\u4f20\u64ad\u75c5\u6bd2\u3002\u5728\u6bcf\u4e00\u5929\uff0c\u4f60\u5fc5\u987b\u5728\u6700\u5927\u7684\u75c5\u6bd2\uff08\u8fde\u901a\u533a\u57df\uff09\u7684\u5468\u56f4\u5efa\u9020\u5899\u963b\u6321\u75c5\u6bd2\u4f20\u64ad\u3002\u95ee\u4f60\u4e00\u5171\u9700\u8981\u591a\u5c11\u4e2a\u5899\u624d\u80fd\u963b\u6321\u6240\u6709\u75c5\u6bd2\u4f20\u64ad\u3002<\/p>\n<h1><strong>Problems:<\/strong><\/h1>\n<p>A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.<\/p>\n<p>The world is modeled as a 2-D array of cells, where\u00a0<code>0<\/code>\u00a0represents uninfected cells, and\u00a0<code>1<\/code>\u00a0represents cells contaminated with the virus. A wall (and only one wall) can be installed\u00a0<b>between any two 4-directionally adjacent cells<\/b>, on the shared boundary.<\/p>\n<p>Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region &#8212; the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night. There will never be a tie.<\/p>\n<p>Can you save the day? If so, what is the number of walls required? If not, and the world becomes fully infected, return the number of walls used.<\/p>\n<h2><b>Example 1:<\/b><\/h2>\n<pre class=\"crayon:false\">Input: grid = \r\n[[0,1,0,0,0,0,0,1],\r\n [0,1,0,0,0,0,0,1],\r\n [0,0,0,0,0,0,0,1],\r\n [0,0,0,0,0,0,0,0]]\r\nOutput: 10\r\nExplanation:\r\nThere are 2 contaminated regions.\r\nOn the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:\r\n\r\n[[0,1,0,0,0,0,1,1],\r\n [0,1,0,0,0,0,1,1],\r\n [0,0,0,0,0,0,1,1],\r\n [0,0,0,0,0,0,0,1]]\r\n\r\nOn the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.\r\n<\/pre>\n<h2><b>Example 2:<\/b><\/h2>\n<pre class=\"crayon:false\">Input: grid = \r\n[[1,1,1],\r\n [1,0,1],\r\n [1,1,1]]\r\nOutput: 4\r\nExplanation: Even though there is only one cell saved, there are 4 walls built.\r\nNotice that walls are only built on the shared boundary of two different cells.\r\n<\/pre>\n<h2><b>Example 3:<\/b><\/h2>\n<pre class=\"crayon:false \">Input: grid = \r\n[[1,1,1,0,0,0,0,0,0],\r\n [1,0,1,0,1,1,1,1,1],\r\n [1,1,1,0,0,0,0,0,0]]\r\nOutput: 13\r\nExplanation: The region on the left only builds two new walls.\r\n<\/pre>\n<h2><b>Note:<\/b><\/h2>\n<ol>\n<li>The number of rows and columns of\u00a0<code>grid<\/code>\u00a0will each be in the range\u00a0<code>[1, 50]<\/code>.<\/li>\n<li>Each\u00a0<code>grid[i][j]<\/code>\u00a0will be either\u00a0<code>0<\/code>\u00a0or\u00a0<code>1<\/code>.<\/li>\n<li>Throughout the described process, there is always a contiguous viral region that will infect\u00a0<b>strictly more<\/b>\u00a0uncontaminated squares in the next round.<\/li>\n<\/ol>\n<p>&nbsp;<\/p>\n<h1><strong>Idea:<\/strong><\/h1>\n<p>Use DFS to find virus regions, next affected regions and # of walls needed to block each virus region.<\/p>\n<p>Simulate the virus expansion process.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1288\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/749-ep136.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/749-ep136.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/749-ep136-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/749-ep136-768x432.png 768w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/p>\n<h1><strong>Solution:<\/strong><\/h1>\n<p>C++ \/ DFS<\/p>\n<p>Time complexity: O(n^3)<\/p>\n<p>Space complexity: O(n^2)<\/p>\n<pre class=\"lang:c++ decode:true\">\/\/ Author: Huahua\r\n\/\/ Runtime: 12 ms\r\nclass Solution {\r\npublic:\r\n  int containVirus(vector&lt;vector&lt;int&gt;&gt;&amp; grid) {\r\n    int m = grid.size();\r\n    int n = grid[0].size();\r\n    int total_walls = 0;\r\n    while (true) {            \r\n      vector&lt;int&gt; visited(m * n, 0);\r\n      vector&lt;int&gt; virus_area;\r\n      vector&lt;unordered_set&lt;int&gt;&gt; nexts;\r\n      int block_index = -1;\r\n      int block_walls = -1;\r\n      for (int i = 0; i &lt; m; ++i)\r\n        for (int j = 0; j &lt; n; ++j) {\r\n          int key = i * n + j;\r\n          if (grid[i][j] != 1 || visited[key]) continue;\r\n          vector&lt;int&gt; curr;\r\n          unordered_set&lt;int&gt; next;\r\n          int walls = 0;\r\n          getArea(j, i, m, n, grid, visited, curr, next, walls);\r\n          if (next.empty()) continue;                    \r\n          if (nexts.empty() || next.size() &gt; nexts[block_index].size()) {\r\n            virus_area.swap(curr);\r\n            block_index = nexts.size();\r\n            block_walls = walls;\r\n          }\r\n          nexts.push_back(std::move(next));\r\n        }\r\n\r\n      if (nexts.empty()) break;\r\n\r\n      total_walls += block_walls;\r\n      for (int i = 0; i &lt; nexts.size(); ++i) {\r\n        if (i == block_index) {\r\n          for (const int key : virus_area) {\r\n              int y = key \/ n;\r\n              int x = key % n;\r\n              grid[y][x] = 2; \/\/ blocked.\r\n          }\r\n        } else {\r\n          for (const int key : nexts[i]) {\r\n              int y = key \/ n;\r\n              int x = key % n;\r\n              grid[y][x] = 1; \/\/ newly affected\r\n          }\r\n        }\r\n      }\r\n    }\r\n    return total_walls;\r\n  }\r\nprivate:\r\n  void getArea(\r\n    int x, int y, int m, int n,\r\n    vector&lt;vector&lt;int&gt;&gt;&amp; grid,\r\n    vector&lt;int&gt;&amp; visited,\r\n    vector&lt;int&gt;&amp; curr,\r\n    unordered_set&lt;int&gt;&amp; next,\r\n    int&amp; walls) {\r\n    static int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};\r\n\r\n    if (x &lt; 0 || x &gt;= n || y &lt; 0 || y &gt;= m || grid[y][x] == 2) return;\r\n\r\n    int key = y * n + x;\r\n    \/\/ need one wall\r\n    if (grid[y][x] == 0) {\r\n      ++walls;\r\n      next.insert(key);\r\n      return;\r\n    }\r\n\r\n    if (visited[key]) return;\r\n    visited[key] = 1;\r\n    curr.push_back(key);    \r\n\r\n    for (int i = 0; i &lt; 4; ++i)\r\n      getArea(x + dirs[i][0], y + dirs[i][1], m, n, grid, visited, curr, next, walls);\r\n  }\r\n};<\/pre>\n<h1><strong>Related Problems:<\/strong><\/h1>\n<ul>\n<li><a href=\"http:\/\/zxi.mytechroad.com\/blog\/searching\/leetcode-200-number-of-islands\/\">[\u89e3\u9898\u62a5\u544a] LeetCode 200. Number of Islands<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>\u9898\u76ee\u5927\u610f\uff1a\u7ed9\u4f60\u4e00\u4e2a\u683c\u5b50\u5730\u56fe\u4e0a\u9762\u6709\u4e00\u4e9b\u75c5\u6bd2\u75281\u8868\u793a\uff0c\u672a\u53d7\u611f\u67d3\u7684\u683c\u5b50\u75280\u8868\u793a\u3002\u5e26\u6709\u75c5\u6bd2\u7684\u683c\u5b50\u6bcf\u5929\u4f1a\u5411\u56db\u5468\u7684\u683c\u5b50\u4f20\u64ad\u75c5\u6bd2\u3002\u5728\u6bcf\u4e00\u5929\uff0c\u4f60\u5fc5\u987b\u5728\u6700\u5927\u7684\u75c5\u6bd2\uff08\u8fde\u901a\u533a\u57df\uff09\u7684\u5468\u56f4\u5efa\u9020\u5899\u963b\u6321\u75c5\u6bd2\u4f20\u64ad\u3002\u95ee\u4f60\u4e00\u5171\u9700\u8981\u591a\u5c11\u4e2a\u5899\u624d\u80fd\u963b\u6321\u6240\u6709\u75c5\u6bd2\u4f20\u64ad\u3002 Problems: A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls. The world is modeled as a&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[44,48],"tags":[33,217,179],"class_list":["post-1280","post","type-post","status-publish","format-standard","hentry","category-searching","category-simulation","tag-dfs","tag-hard","tag-simulation","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1280","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=1280"}],"version-history":[{"count":12,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1280\/revisions"}],"predecessor-version":[{"id":2123,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1280\/revisions\/2123"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=1280"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=1280"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=1280"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}