1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| class Solution { public int findCircleNum(int[][] M) { int result = 0; boolean[] visited = new boolean[M.length]; for (int i = 0; i < M.length; i++) { if (visited[i] == false) { dfs(M, visited, i); result++; } } return result; }
private void dfs(int[][] M, boolean[] visited, int start) { for (int i = 0; i < M.length; i++) { if (M[i][start] == 1 && visited[i] == false) { visited[i] = true; dfs(M, visited, i); } } } }
class Solution { public int findCircleNum(int[][] M) { int result = 0; boolean[] visited = new boolean[M.length]; Queue<Integer> queue = new LinkedList<>(); for (int i = 0; i < M.length; i++) { if (visited[i] == false) { queue.add(i); while (!queue.isEmpty()) { int num = queue.remove(); visited[num]=true; for (int j = 0; j < M.length; j++) { if (M[num][j] == 1 && visited[j] == false) { queue.add(j); } } } result++; } } return result; } }
class Solution { public int findCircleNum(int[][] M) { int result = 0; int[] parent = new int[M.length]; Arrays.fill(parent, -1); for (int i = 0; i < M.length; i++) { for (int j = 0; j < M.length; j++) { if (M[i][j] == 1 && i != j) { union(parent, i, j); } } } for (int i = 0; i < M.length; i++) { if (parent[i] == -1) { result++; } } return result; }
private void union(int[] parent, int i, int j) { int fX = find(parent, i); int fY = find(parent, j); if (fX != fY) { parent[fX] = fY; } }
private int find(int[] parent, int x) { if (parent[x] == -1) { return x; } return find(parent, parent[x]); } }
|