-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetcode_947.java
53 lines (45 loc) · 1.64 KB
/
Leetcode_947.java
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
class Solution {
public int removeStones(int[][] stones) {
int n = stones.length;
// Adjacency list to store graph connections
List<Integer>[] adjacencyList = new List[n];
for (int i = 0; i < n; i++) {
adjacencyList[i] = new ArrayList<>();
}
// Build the graph: Connect stones that share the same row or column
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (
stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1]
) {
adjacencyList[i].add(j);
adjacencyList[j].add(i);
}
}
}
int numOfConnectedComponents = 0;
boolean[] visited = new boolean[n];
// Traverse all stones using DFS to count connected components
for (int i = 0; i < n; i++) {
if (!visited[i]) {
depthFirstSearch(adjacencyList, visited, i);
numOfConnectedComponents++;
}
}
// Maximum stones that can be removed is total stones minus number of connected components
return n - numOfConnectedComponents;
}
// DFS to visit all stones in a connected component
private void depthFirstSearch(
List<Integer>[] adjacencyList,
boolean[] visited,
int stone
) {
visited[stone] = true;
for (int neighbor : adjacencyList[stone]) {
if (!visited[neighbor]) {
depthFirstSearch(adjacencyList, visited, neighbor);
}
}
}
}