码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 547. Friend Circles 朋友圈

时间:2020-04-13 00:57:47      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:ast   app   遍历   并查集   pre   friend   朋友圈   wan   不同的   

      本题可以套用和 [LeetCode] 200. Number of Islands 岛屿的数量 与 [LeetCode 695] Max Area of Island 岛的最大面积一样的dfs模版,不同的是DFS的遍历路径不同,本题

采用的是类似十字遍历方式,具体见如下代码,本题同样可以使用BFS和并查集的方法解决,这里暂不讨论;

 1 /*
 2  * @Descripttion: 
 3  * @version: 
 4  * @Author: wangxf
 5  * @Date: 2019-12-20 15:21:49
 6  * @LastEditors: Do not edit
 7  * @LastEditTime: 2020-04-12 23:25:24
 8  */
 9 /*
10  * @lc app=leetcode.cn id=547 lang=cpp
11  *
12  * [547] 朋友圈
13  */
14 
15 // @lc code=start
16 #include<bits/stdc++.h>
17 using namespace std;
18 class Solution {
19 public:
20     int findCircleNum(vector<vector<int>>& M)
21     {
22         int res = 0;
23         if(M.empty()||M.size()<=0) return 0;
24         for (size_t i = 0; i < M.size(); i++)
25             for (size_t j = 0; j < M[0].size(); j++)
26             {
27                 /*
28                 if(i==j)
29                 {
30                   //++res;
31                   continue;
32                 }
33                 */ 
34                 if(M[i][j]==1)
35                 {
36                     ++res;
37                     dfs(M,i,j);
38                 }
39             }
40         return res;  
41     }
42     void dfs(vector<vector<int>>& M,int i,int j)
43     {
44         if(!(i>=0&&i<M.size()&&j>=0&&j<M[0].size()))
45         {
46             return;
47         }
48         if(M[i][j]==0)
49         {
50             return;
51         }
52         M[i][j]=0;
53         //if(i==j) return;
54 
55         for(int r = 0;r<M.size();++r)
56         {
57             if(M[r][j]==1&&r!=i)
58             {
59                 dfs(M,r,j);
60             }
61         }
62         for(int c = 0;c<M[0].size();++c)
63         {
64             if(M[i][c]==1&&c!=j)
65             {
66                 dfs(M,i,c);
67             }
68         }
69         return;
70     }
71 };
72 // @lc code=end

 

[LeetCode] 547. Friend Circles 朋友圈

标签:ast   app   遍历   并查集   pre   friend   朋友圈   wan   不同的   

原文地址:https://www.cnblogs.com/wangxf2019/p/12688668.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!