{"id":382,"date":"2017-09-21T21:29:41","date_gmt":"2017-09-22T04:29:41","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=382"},"modified":"2018-08-31T12:37:38","modified_gmt":"2018-08-31T19:37:38","slug":"leetcode-547-friend-circles","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/graph\/leetcode-547-friend-circles\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 547. Friend Circles"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 547. Friend Circles - \u5237\u9898\u627e\u5de5\u4f5c EP67\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/HHiHno66j40?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><strong>Problem:<\/strong><\/p>\n<p>There are\u00a0<b>N<\/b>\u00a0students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a\u00a0<b>direct<\/b>\u00a0friend of B, and B is a\u00a0<b>direct<\/b>\u00a0friend of C, then A is an\u00a0<b>indirect<\/b>\u00a0friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.<\/p>\n<p>Given a\u00a0<b>N*N<\/b>\u00a0matrix\u00a0<b>M<\/b>\u00a0representing the friend relationship between students in the class. If M[i][j] = 1, then the i<sub>th<\/sub>and j<sub>th<\/sub>\u00a0students are\u00a0<b>direct<\/b>\u00a0friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.<\/p>\n<p><b>Example 1:<\/b><\/p>\n<pre class=\"\">Input: \r\n[[1,1,0],\r\n [1,1,0],\r\n [0,0,1]]\r\nOutput: 2\r\n<\/pre>\n<p>E<b>xample 2:<\/b><\/p>\n<pre class=\"\">Input: \r\n[[1,1,0],\r\n [1,1,1],\r\n [0,1,1]]\r\nOutput: 1<\/pre>\n<ol>\n<li>N is in range [1,200].<\/li>\n<li>M[i][i] = 1 for all students.<\/li>\n<li>If M[i][j] = 1, then M[j][i] = 1.<\/li>\n<\/ol>\n<p><strong>Idea:<\/strong><\/p>\n<p>Find all connected components using DFS<\/p>\n<p><script async src=\"\/\/pagead2.googlesyndication.com\/pagead\/js\/adsbygoogle.js\"><\/script><br \/>\n<ins class=\"adsbygoogle\" style=\"display: block; text-align: center;\" data-ad-layout=\"in-article\" data-ad-format=\"fluid\" data-ad-client=\"ca-pub-2404451723245401\" data-ad-slot=\"7983117522\"><\/ins><br \/>\n<script>\n     (adsbygoogle = window.adsbygoogle || []).push({});\n<\/script><\/p>\n<h1><strong>Solution: DFS<\/strong><\/h1>\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:c++ decode:true\">\/\/ Author: Huahua\r\n\/\/ Time complexity: O(n^2)\r\n\/\/ Space complexity: O(n)\r\n\/\/ Running Time: 25 ms\r\nclass Solution {\r\npublic:\r\n    int findCircleNum(vector&lt;vector&lt;int&gt;&gt;&amp; M) {\r\n        if (M.empty()) return 0;\r\n        int n = M.size();\r\n        int ans = 0;\r\n        for (int i = 0; i &lt; n; ++i) {\r\n            if (!M[i][i]) continue;\r\n            ++ans;\r\n            dfs(M, i, n);\r\n        }\r\n        return ans;\r\n    }\r\nprivate:\r\n    void dfs(vector&lt;vector&lt;int&gt;&gt;&amp; M, int curr, int n) {        \r\n        \/\/ Visit all friends (neighbors)\r\n        for (int i = 0; i &lt; n; ++i) {\r\n            if (!M[curr][i]) continue;\r\n            M[curr][i] = M[i][curr] = 0;\r\n            dfs(M, i, n);\r\n        }\r\n    }\r\n};<\/pre>\n\n<\/div><h2 class=\"tabtitle\">Java<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:java decode:true\">\/\/ Author: Huahua\r\n\/\/ Time complexity: O(n^2)\r\n\/\/ Space complexity: O(n)\r\n\/\/ Running Time: 20 ms\r\nclass Solution {\r\n    public int findCircleNum(int[][] M) {\r\n        int n = M.length;\r\n        if (n == 0) return 0;\r\n        \r\n        int ans = 0;\r\n        for (int i = 0; i &lt; n; ++i) {\r\n            if (M[i][i] == 0) continue;            \r\n            ++ans;\r\n            dfs(M, i, n);\r\n        }\r\n        return ans;\r\n    }\r\n    \r\n    private void dfs(int[][] M, int curr, int n) {\r\n        for (int i = 0; i &lt; n; ++i) {\r\n            if (M[curr][i] == 0) continue;\r\n            M[curr][i] = M[i][curr] = 0;\r\n            dfs(M, i, n);\r\n        }\r\n    }\r\n}<\/pre>\n\n<\/div><h2 class=\"tabtitle\">Python<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:python decode:true \">\"\"\"\r\nAuthor: Huahua\r\nTime complexity: O(n^2)\r\nSpace complexity: O(n)\r\nRunning Time: 162 ms\r\n\"\"\"\r\nclass Solution(object):\r\n    def findCircleNum(self, M):\r\n        \"\"\"\r\n        :type M: List[List[int]]\r\n        :rtype: int\r\n        \"\"\"\r\n        \r\n        def dfs(M, curr, n):\r\n            for i in xrange(n):\r\n                if M[curr][i] == 1:\r\n                    M[curr][i] = M[i][curr] = 0\r\n                    dfs(M, i, n)\r\n        \r\n        n = len(M)\r\n        ans = 0\r\n        for i in xrange(n):\r\n            if M[i][i] == 1:\r\n                ans += 1\r\n                dfs(M, i, n)\r\n        \r\n        return ans<\/pre>\n<\/div><\/div>\n<h1><strong>Solution 2: <a href=\"https:\/\/zxi.mytechroad.com\/blog\/data-structure\/sp1-union-find-set\/\">Union Find<\/a><\/strong><\/h1>\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:default decode:true\">\/\/ Author: Huahua\r\n\/\/ Runtime: 19 ms\r\nclass UnionFindSet {\r\npublic:\r\n    UnionFindSet(int n) {\r\n        parents_ = vector&lt;int&gt;(n + 1, 0);\r\n        ranks_ = vector&lt;int&gt;(n + 1, 0);\r\n        \r\n        for (int i = 0; i &lt; parents_.size(); ++i)\r\n            parents_[i] = i;\r\n    }\r\n    \r\n    bool Union(int u, int v) {\r\n        int pu = Find(u);\r\n        int pv = Find(v);\r\n        if (pu == pv) return false;\r\n        \r\n        if (ranks_[pu] &gt; ranks_[pv]) {\r\n            parents_[pv] = pu;\r\n        } else if (ranks_[pv] &gt; ranks_[pu]) {\r\n            parents_[pu] = pv;\r\n        } else {\r\n            parents_[pu] = pv;\r\n            ++ranks_[pv];\r\n        }\r\n \r\n        return true;\r\n    }\r\n    \r\n    int Find(int id) {        \r\n        if (id != parents_[id])\r\n            parents_[id] = Find(parents_[id]);        \r\n        return parents_[id];\r\n    }\r\n    \r\nprivate:\r\n    vector&lt;int&gt; parents_;\r\n    vector&lt;int&gt; ranks_;\r\n};\r\n \r\nclass Solution {\r\npublic:\r\n    int findCircleNum(vector&lt;vector&lt;int&gt;&gt;&amp; M) {\r\n        int n = M.size();\r\n        UnionFindSet s(n);\r\n        for (int i = 0; i &lt; n; ++i)\r\n            for (int j = i + 1; j &lt; n; ++j)\r\n                if (M[i][j] == 1) s.Union(i, j);\r\n        \r\n        unordered_set&lt;int&gt; circles;\r\n        for (int i = 0; i &lt; n; ++i)\r\n            circles.insert(s.Find(i));\r\n        \r\n        return circles.size();\r\n    }\r\n};<\/pre>\n<\/div><\/div>\n<p>&nbsp;<\/p>\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<li><a href=\"http:\/\/zxi.mytechroad.com\/blog\/graph\/leetcode-695-max-area-of-island\/\">[\u89e3\u9898\u62a5\u544a] LeetCode 695. Max Area of Island<\/a><\/li>\n<li><a href=\"http:\/\/zxi.mytechroad.com\/blog\/tree\/leetcode-684-redundant-connection\/\">[\u89e3\u9898\u62a5\u544a] LeetCode 684. Redundant Connection<\/a><\/li>\n<li><a href=\"http:\/\/zxi.mytechroad.com\/blog\/graph\/leetcode-685-redundant-connection-ii\/\">[\u89e3\u9898\u62a5\u544a] LeetCode 685. Redundant Connection II<\/a><\/li>\n<li><a href=\"http:\/\/zxi.mytechroad.com\/blog\/hashtable\/leetcode-737-sentence-similarity-ii\/\">[\u89e3\u9898\u62a5\u544a] LeetCode 737. Sentence Similarity II<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Problem: There are\u00a0N\u00a0students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if 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":[76],"tags":[102,33,177,101,113],"class_list":["post-382","post","type-post","status-publish","format-standard","hentry","category-graph","tag-connected-components","tag-dfs","tag-medium","tag-scc","tag-union-find","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/382","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=382"}],"version-history":[{"count":14,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/382\/revisions"}],"predecessor-version":[{"id":3792,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/382\/revisions\/3792"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=382"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=382"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=382"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}