本題能夠套用和 [LeetCode] 200. Number of Islands 島嶼的數量 與 [LeetCode 695] Max Area of Island 島的最大面積同樣的dfs模版,不一樣的是DFS的遍歷路徑不一樣,本題html
採用的是相似十字遍歷方式,具體見以下代碼,本題一樣能夠使用BFS和並查集的方法解決,這裏暫不討論;c++
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