Skip to content

Commit

Permalink
22
Browse files Browse the repository at this point in the history
  • Loading branch information
douhaopeng committed Apr 23, 2020
1 parent 76c2f04 commit 62f850a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
22 changes: 22 additions & 0 deletions 547.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
public class Solution {
public int findCircleNum(int[][] M) {
boolean visited[] = new boolean[M.length];
int cycle = 0;
for(int i = 0; i < M.length; i ++){
if(!visited[i]){
cycle++;
visited[i] = true;
dfs(M, visited, i);//dfs to mark all ppl in the cycle visited
}
}
return cycle;
}
public void dfs(int[][] M, boolean[] visited, int i){
for(int j = 0; j < M[0].length; j++){//no return case here!!
if(!visited[j] && M[i][j] == 1){
visited[j] = true;
dfs(M, visited, j);
}
}
}
}
23 changes: 23 additions & 0 deletions 547_2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
public class Solution{

public int findCircleNum(int [][] M){
boolean visited[] = new boolean[M.length];
int cycle = 0;
for(int i =0; i<M.length;i++){
if(!visited[i]){
cycle++;
visited[i] = true;
dfs(M,visited,i);
}
}
return cycle;
}
public void dfs(int[][] M,boolean[] visited,int i){
for(int j = 0;j<M[0].length;j++){
if(!visited[j] && M[i][j] ==1){
visited[j] = true;
dfs(M,visited,j);
}
}
}
}

0 comments on commit 62f850a

Please sign in to comment.