Skip to content

Commit f03a10c

Browse files
authored
Add files via upload
1 parent d24ea8b commit f03a10c

File tree

1 file changed

+105
-0
lines changed

1 file changed

+105
-0
lines changed

Islands2.java

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
package PracticeGraphs;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
import java.util.Scanner;
7+
8+
public class Islands2 {
9+
10+
public static int findParent(int node, int parent[]) {
11+
if (node == parent[node]) {
12+
return node;
13+
}
14+
return parent[node] = findParent(parent[node], parent);
15+
}
16+
17+
public static void union(int u, int v, int parent[]) {
18+
int ulp = findParent(u, parent); // Find parent of u
19+
int vlp = findParent(v, parent); // Find parent of v
20+
if (ulp != vlp) {
21+
parent[ulp] = vlp; // Union
22+
}
23+
}
24+
25+
public static List<Integer> fun(int[][] arr, int[][] arr2) {
26+
int n = arr.length;
27+
int m = arr[0].length;
28+
29+
int parent[] = new int[n * m];
30+
Arrays.fill(parent, -1);
31+
32+
int components = 0;
33+
List<Integer> islands = new ArrayList<>();
34+
35+
// Directions for exploring neighbors (up, right, down, left)
36+
int dx[] = {-1, 0, 1, 0};
37+
int dy[] = {0, 1, 0, -1};
38+
39+
for (int[] it : arr2) {
40+
int x = it[0];
41+
int y = it[1];
42+
int cell = x * m + y;
43+
44+
// If already land, return current number of components
45+
if (parent[cell] != -1) {
46+
islands.add(components);
47+
continue;
48+
}
49+
50+
// Add new land
51+
parent[cell] = cell;
52+
components++;
53+
54+
// Check neighbors
55+
for (int i = 0; i < 4; i++) {
56+
int nx = x + dx[i];
57+
int ny = y + dy[i];
58+
59+
if (nx >= 0 && nx < n && ny >= 0 && ny < m) {
60+
int neighbor = nx * m + ny;
61+
62+
if (parent[neighbor] != -1) { // Neighbor is part of the grid
63+
int parentCell = findParent(cell, parent);
64+
int parentNeighbor = findParent(neighbor, parent);
65+
66+
if (parentCell != parentNeighbor) {
67+
union(cell, neighbor, parent);
68+
components--; // Merge reduces the number of components
69+
}
70+
}
71+
}
72+
}
73+
islands.add(components);
74+
}
75+
76+
return islands;
77+
}
78+
79+
public static void main(String[] args) {
80+
Scanner sc = new Scanner(System.in);
81+
82+
int n = sc.nextInt();
83+
int m = sc.nextInt();
84+
85+
int arr[][] = new int[n][m]; // Initial grid
86+
87+
for (int i = 0; i < n; i++) {
88+
for (int j = 0; j < m; j++) {
89+
arr[i][j] = sc.nextInt();
90+
}
91+
}
92+
93+
int n2 = sc.nextInt();
94+
int arr2[][] = new int[n2][2];
95+
96+
for (int i = 0; i < n2; i++) {
97+
for (int j = 0; j < 2; j++) {
98+
arr2[i][j] = sc.nextInt();
99+
}
100+
}
101+
102+
System.out.println(fun(arr, arr2));
103+
sc.close();
104+
}
105+
}

0 commit comments

Comments
 (0)