public class Solution { private void dfs(int[,] M, int[] visited, int i) { for (int j = 0; j < M.GetLength(1); j++) { if (M[i, j] == 1 && visited[j] == 0) { visited[j] = 1; dfs(M, visited, j); } } } public int FindCircleNum(int[,] M) { int[] visited = new int[M.GetLength(0)]; int count = 0; for (int i = 0; i < M.GetLength(0); i++) { if (visited[i] == 0) { dfs(M, visited, i); count++; } } return count; } }
这是第一种方法,主要是使用dfs来实现。
下面是第二种方法,是同学用python写的,我翻译成了C#,这种思路是union find。
public class Solution { public int FindCircleNum(int[,] M) { var N = M.GetLength(0); var groups = N; var leads = new int[N]; for (var i = 0; i < N; i++) { leads[i] = i; } for (var i = 0; i < N; i++) { for (var j = i + 1; j < N; j++) { if (M[i, j] == 1) { var lead1 = find(i, leads); var lead2 = find(j, leads); if (lead1 != lead2) { leads[lead1] = lead2; groups--; } } } } return groups; } private int find(int x, int[] parents) { if (parents[x] == x) { return x; } else { return find(parents[x], parents); } } }
从耗时角度来看,第一种效率略高一些。