|
1 | 1 | import java.util.*; |
| 2 | + |
2 | 3 | class Solution { |
3 | | - static boolean[] visited; |
4 | | - static ArrayList<Integer>[] A; |
5 | | - static int max; |
| 4 | + |
| 5 | + static ArrayList<Integer> list[]; |
| 6 | + static boolean visited[]; |
6 | 7 | public int solution(int n, int[][] computers) { |
7 | 8 | int answer = 0; |
8 | | - max =1; |
9 | | - visited = new boolean[n+1]; |
10 | | - |
11 | | - A = new ArrayList[n+1]; |
12 | | - |
13 | | - for(int i =1; i<=n; i++) |
14 | | - { |
15 | | - A[i] = new ArrayList<Integer>(); |
| 9 | + |
| 10 | + list = new ArrayList[n+1]; |
| 11 | + |
| 12 | + for(int i =1; i<=n; i++) { |
| 13 | + list[i] = new ArrayList<Integer>(); |
16 | 14 | } |
17 | | - |
18 | | - for (int i = 0; i < n; i++) { |
19 | | - for (int j = 0; j < n; j++) { |
20 | | - if (computers[i][j] == 1) { // If there's a connection between i and j |
21 | | - A[i+1].add(j+1); // Adjust indices because i and j are zero-based |
| 15 | + visited = new boolean[n+1]; |
| 16 | + for(int i =0; i<computers.length; i++) { |
| 17 | + for(int j =0; j<computers[i].length;j++) { |
| 18 | + if(computers[i][j] == 1) { |
| 19 | + list[i+1].add(j+1); |
| 20 | + list[j+1].add(i+1); |
22 | 21 | } |
23 | 22 | } |
24 | 23 | } |
25 | 24 |
|
26 | | - for(int i =1; i<=n; i++) |
27 | | - { |
28 | | - if(visited[i]==false) |
29 | | - { |
30 | | - dfs(i); |
31 | | - answer++; |
32 | | - |
| 25 | + for(int i =1; i<=n; i++) { |
| 26 | + if(!visited[i]){ |
| 27 | + bfs(i); |
| 28 | + answer+=1; |
33 | 29 | } |
34 | 30 | } |
| 31 | + |
35 | 32 | return answer; |
36 | 33 | } |
37 | | - static void dfs(int value) |
38 | | - { |
39 | | - if(visited[value]) |
40 | | - return; |
41 | | - |
| 34 | + static void bfs(int start) { |
| 35 | + |
42 | 36 | Queue<Integer> queue = new LinkedList<>(); |
| 37 | + |
| 38 | + queue.add(start); |
43 | 39 |
|
44 | | - visited[value]=true; |
45 | | - queue.add(value); |
46 | | - |
47 | | - while(!queue.isEmpty()) |
48 | | - { |
49 | | - int now =queue.poll(); |
50 | | - max=now; |
51 | | - for(int i : A[now]) |
52 | | - { |
53 | | - if(visited[i]==false) |
54 | | - { |
55 | | - visited[i]=true; |
56 | | - queue.add(i); |
| 40 | + while(!queue.isEmpty()) { |
| 41 | + int now = queue.poll(); |
| 42 | + |
| 43 | + for(int cur : list[now]) { |
| 44 | + if(!visited[cur]) { |
| 45 | + queue.add(cur); |
| 46 | + visited[cur] = true; |
57 | 47 | } |
58 | 48 | } |
59 | 49 | } |
|
0 commit comments