|
37 | 37 | */ |
38 | 38 | public class _547 { |
39 | 39 |
|
40 | | - public int findCircleNum(int[][] M) { |
41 | | - if (M == null || M.length == 0 || M[0].length == 0) { |
42 | | - return 0; |
43 | | - } |
44 | | - int m = M.length;//number of rows in this matrix |
45 | | - UnionFind unionFind = new UnionFind(m); |
46 | | - for (int i = 0; i < m; i++) { |
47 | | - for (int j = i + 1; j < m; j++) { |
48 | | - if (M[i][j] == 1) { |
49 | | - unionFind.union(i, j); |
| 40 | + public static class Solution1 { |
| 41 | + public int findCircleNum(int[][] M) { |
| 42 | + if (M == null || M.length == 0 || M[0].length == 0) { |
| 43 | + return 0; |
| 44 | + } |
| 45 | + int m = M.length;//number of rows in this matrix |
| 46 | + UnionFind unionFind = new UnionFind(m); |
| 47 | + for (int i = 0; i < m; i++) { |
| 48 | + for (int j = i + 1; j < m; j++) { |
| 49 | + if (M[i][j] == 1) { |
| 50 | + unionFind.union(i, j); |
| 51 | + } |
50 | 52 | } |
51 | 53 | } |
| 54 | + return unionFind.count; |
52 | 55 | } |
53 | | - return unionFind.count; |
54 | | - } |
55 | 56 |
|
56 | | - class UnionFind { |
57 | | - int count; |
58 | | - int[] root; |
| 57 | + class UnionFind { |
| 58 | + int count; |
| 59 | + int[] root; |
59 | 60 |
|
60 | | - public UnionFind(int m) { |
61 | | - root = new int[m]; |
62 | | - for (int i = 0; i < m; i++) { |
63 | | - root[i] = i; |
| 61 | + public UnionFind(int m) { |
| 62 | + root = new int[m]; |
| 63 | + for (int i = 0; i < m; i++) { |
| 64 | + root[i] = i; |
| 65 | + } |
| 66 | + count = m; |
64 | 67 | } |
65 | | - count = m; |
66 | | - } |
67 | 68 |
|
68 | | - public void union(int i, int j) { |
69 | | - int x = find(root, i); |
70 | | - int y = find(root, j); |
71 | | - if (x != y) { |
72 | | - count--; |
73 | | - root[x] = y;//path compression |
| 69 | + public void union(int i, int j) { |
| 70 | + int x = find(root, i); |
| 71 | + int y = find(root, j); |
| 72 | + if (x != y) { |
| 73 | + count--; |
| 74 | + root[x] = y;//path compression |
| 75 | + } |
74 | 76 | } |
75 | | - } |
76 | 77 |
|
77 | | - public int find(int[] ids, int i) { |
78 | | - if (ids[i] == i) { |
79 | | - return i; |
| 78 | + public int find(int[] ids, int i) { |
| 79 | + if (ids[i] == i) { |
| 80 | + return i; |
| 81 | + } |
| 82 | + return find(ids, ids[i]); |
80 | 83 | } |
81 | | - return find(ids, ids[i]); |
82 | 84 | } |
83 | 85 | } |
84 | 86 |
|
|
0 commit comments