-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
76c2f04
commit 62f850a
Showing
2 changed files
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} | ||
} |