{"id":7290,"date":"2020-08-23T01:46:10","date_gmt":"2020-08-23T08:46:10","guid":{"rendered":"https:\/\/zxi.mytechroad.com\/blog\/?p=7290"},"modified":"2020-08-23T01:47:00","modified_gmt":"2020-08-23T08:47:00","slug":"leetcode-1559-detect-cycles-in-2d-grid","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/graph\/leetcode-1559-detect-cycles-in-2d-grid\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 1559. Detect Cycles in 2D Grid"},"content":{"rendered":"\n<p>Given a 2D array of characters&nbsp;<code>grid<\/code>&nbsp;of size&nbsp;<code>m x n<\/code>, you need to find if there exists any cycle consisting of the&nbsp;<strong>same value<\/strong>&nbsp;in&nbsp;<code>grid<\/code>.<\/p>\n\n\n\n<p>A cycle is a path of&nbsp;<strong>length 4&nbsp;or more<\/strong>&nbsp;in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it &#8211; in one of the four directions (up, down, left, or right), if it has the&nbsp;<strong>same value<\/strong>&nbsp;of the current cell.<\/p>\n\n\n\n<p>Also, you cannot move to the cell that you visited in your last move. For example, the cycle&nbsp;<code>(1, 1) -&gt; (1, 2) -&gt; (1, 1)<\/code>&nbsp;is invalid because from&nbsp;<code>(1, 2)<\/code>&nbsp;we visited&nbsp;<code>(1, 1)<\/code>&nbsp;which was the last visited cell.<\/p>\n\n\n\n<p>Return&nbsp;<code>true<\/code>&nbsp;if any cycle of the same value exists in&nbsp;<code>grid<\/code>, otherwise, return&nbsp;<code>false<\/code>.<\/p>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/assets.leetcode.com\/uploads\/2020\/07\/15\/1.png\" alt=\"\"\/><\/figure>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> grid = [[\"a\",\"a\",\"a\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"a\",\"a\",\"a\"]]\n<strong>Output:<\/strong> true\n<strong>Explanation: <\/strong>There are two valid cycles shown in different colors in the image below:\n\n<\/pre>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/assets.leetcode.com\/uploads\/2020\/07\/15\/22.png\" alt=\"\"\/><\/figure>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> grid = [[\"c\",\"c\",\"c\",\"a\"],[\"c\",\"d\",\"c\",\"c\"],[\"c\",\"c\",\"e\",\"c\"],[\"f\",\"c\",\"c\",\"c\"]]\n<strong>Output:<\/strong> true\n<strong>Explanation: <\/strong>There is only one valid cycle highlighted in the image below:\n\n<\/pre>\n\n\n\n<p><strong>Example 3:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/assets.leetcode.com\/uploads\/2020\/07\/15\/3.png\" alt=\"\"\/><\/figure>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> grid = [[\"a\",\"b\",\"b\"],[\"b\",\"z\",\"b\"],[\"b\",\"b\",\"a\"]]\n<strong>Output:<\/strong> false\n<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>m == grid.length<\/code><\/li><li><code>n == grid[i].length<\/code><\/li><li><code>1 &lt;= m &lt;= 500<\/code><\/li><li><code>1 &lt;= n &lt;= 500<\/code><\/li><li><code>grid<\/code>&nbsp;consists only of lowercase&nbsp;English letters.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Solution: DFS<\/strong><\/h2>\n\n\n\n<p>Finding a cycle in an undirected graph => visiting a node that has already been visited and it&#8217;s not the parent node of the current node.<br>b b<br>b b<br>null -> (0, 0) -> (0, 1) -> (1, 1) -> (1, 0) -> (0, 0)<br>The second time we visit (0, 0) which has already been visited before and it&#8217;s not the parent of the current node (1, 0) ( (1, 0)&#8217;s parent is (1, 1) ) which means we found a cycle.<\/p>\n\n\n\n<p>Time complexity: O(m*n)<br>Space complexity: O(m*n)<\/p>\n\n\n\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre lang=\"c++\">\nclass Solution {\npublic:\n  bool containsCycle(vector<vector<char>>& grid) {\n    const int m = grid.size();\n    const int n = grid[0].size();\n    vector<vector<int>> seen(m, vector<int>(n));\n    vector<int> dirs{0, 1, 0, -1, 0};\n    function<bool(int, int, int, int)> dfs = [&](int i, int j, int pi, int pj) {\n      ++seen[i][j];\n      for (int d = 0; d < 4; ++d) {\n        int ni = i + dirs[d];\n        int nj = j + dirs[d + 1];\n        if (ni < 0 || nj < 0 || ni >= m || nj >= n) continue;\n        if (grid[ni][nj] != grid[i][j]) continue;\n        if (!seen[ni][nj]) {\n          if (dfs(ni, nj, i, j)) return true;\n        } else if (ni != pi || nj != pj) {\n          return true;\n        }       \n      }\n      return false;\n    };    \n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        if (!seen[i][j]++ &#038;&#038; dfs(i, j, -1, -1)) \n          return true;\n    return false;\n  }\n};\n<\/pre>\n<\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Given a 2D array of characters&nbsp;grid&nbsp;of size&nbsp;m x n, you need to find if there exists any cycle consisting of the&nbsp;same value&nbsp;in&nbsp;grid. A cycle is&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[76],"tags":[123,33,77,217],"class_list":["post-7290","post","type-post","status-publish","format-standard","hentry","category-graph","tag-cycle","tag-dfs","tag-graph","tag-hard","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/7290","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=7290"}],"version-history":[{"count":3,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/7290\/revisions"}],"predecessor-version":[{"id":7293,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/7290\/revisions\/7293"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=7290"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=7290"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=7290"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}