Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1bb0219

Browse files
solves #1584: Min Cost to Connect All Points in java
1 parent 015cc5f commit 1bb0219

File tree

3 files changed

+135
-40
lines changed

3 files changed

+135
-40
lines changed

β€ŽREADME.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -619,6 +619,7 @@
619619
| 1572 | [Matrix Diagonal Sum](https://leetcode.com/problems/matrix-diagonal-sum) | [![Java](assets/java.png)](src/MatrixDiagonalSum.java) | |
620620
| 1576 | [Replace All ?'s to Avoid Consecutive Repeating Characters](https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters) | [![Java](assets/java.png)](src/ReplaceAllToAvoidConsecutiveRepeatingCharacters.java) | |
621621
| 1582 | [Special Positions in a Binary Matrix](https://leetcode.com/problems/special-positions-in-a-binary-matrix) | [![Java](assets/java.png)](src/SpecialPositionInABinaryMatrix.java) | |
622+
| 1584 | [Min Cost to Connect All Points](https://leetcode.com/problems/min-cost-to-connect-all-points) | [![Java](assets/java.png)](src/MinCostToConnectAllPoints.java) | |
622623
| 1588 | [Sum of All Odd Length Subarrays](https://leetcode.com/problems/sum-of-all-odd-length-subarrays) | [![Java](assets/java.png)](src/SumOfAllOddLengthSubArrays.java) | |
623624
| 1592 | [Rearrange Spaces Between Words](https://leetcode.com/problems/rearrange-spaces-between-words) | [![Java](assets/java.png)](src/RearrangeSpacesBetweenWords.java) | |
624625
| 1598 | [Crawler Log Folder](https://leetcode.com/problems/crawler-log-folder) | [![Java](assets/java.png)](src/CrawlerLogFolder.java) | |

β€Žsrc/HelloWorld.java

Lines changed: 52 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -2,65 +2,77 @@
22
// S: O(N)
33

44
import java.security.cert.Certificate;
5+
import java.util.ArrayList;
56
import java.util.LinkedList;
7+
import java.util.List;
68
import java.util.Queue;
79

810

911

1012
public class HelloWorld {
11-
public static class Node {
12-
public int val;
13-
public Node left;
14-
public Node right;
15-
public Node next;
13+
private static final List<List<Integer>> DIRECTIONS = List.of(
14+
List.of(1, 0),
15+
List.of(0, 1),
16+
List.of(-1, 0),
17+
List.of(0, -1)
18+
);
1619

17-
public Node() {}
20+
public int orangesRotting(int[][] grid) {
21+
final Queue<int[]> queue = new LinkedList<>();
22+
addRottenOrangesToQueue(queue, grid);
23+
int maxTime = 0;
1824

19-
publicNode(int_val) {
20-
val = _val;
21-
}
25+
while (!queue.isEmpty()) {
26+
finalint[] info = queue.poll();
27+
finalintrow = info[0], column = info[1], time = info[2];
2228

23-
public Node(int _val, Node _left, Node _right, Node _next) {
24-
val = _val;
25-
left = _left;
26-
right = _right;
27-
next = _next;
28-
}
29-
};
29+
if (grid[row][column] == 0) {
30+
continue;
31+
}
3032

31-
public Node connect(Node root) {
32-
if (root == null) {
33-
return null;
33+
maxTime = Math.max(time, maxTime);
34+
grid[row][column] = 0;
35+
36+
for (int[] neighbour : getNeighbours(grid, row, column)) {
37+
queue.add(new int[] { neighbour[0], neighbour[1], time + 1});
38+
}
3439
}
3540

36-
final Queue<Node> queue = new LinkedList<>();
37-
queue.add(root);
38-
queue.add(null);
39-
Node current = null;
41+
if (containsFreshOranges(grid)) {
42+
return -1;
43+
}
44+
return maxTime;
45+
}
4046

41-
while (!queue.isEmpty()) {
42-
final Node node = queue.poll();
43-
if (node == null) {
44-
if (!queue.isEmpty()) {
45-
queue.add(null);
46-
current = null;
47+
private static boolean containsFreshOranges(int[][] grid) {
48+
for (int[] row : grid) {
49+
for (int orange : row) {
50+
if (orange == 1) {
51+
return true;
4752
}
48-
continue;
4953
}
54+
}
55+
return false;
56+
}
5057

51-
addChildrenToQueue(queue, node);
52-
53-
if (current != null) {
54-
current.next = node;
58+
private static void addRottenOrangesToQueue(Queue<int[]> queue, int[][] grid) {
59+
for(int row = 0 ; row < grid.length ; row++) {
60+
for (int column = 0 ; column < grid[0].length ; column++) {
61+
if (grid[row][column] == 2) {
62+
queue.add(new int[] { row, column, 0 });
63+
}
5564
}
56-
current = node;
5765
}
58-
59-
return root;
6066
}
6167

62-
private static void addChildrenToQueue(Queue<Node> queue, Node node) {
63-
if (node.left != null) queue.add(node.left);
64-
if (node.right != null) queue.add(node.right);
68+
private static List<int[]> getNeighbours(int[][] grid, int row, int column) {
69+
final List<int[]> result = new ArrayList<>();
70+
for (List<Integer> direction : DIRECTIONS) {
71+
final int r = row + direction.get(0), c = column + direction.get(1);
72+
if (r >= 0 && r < grid.length && c >= 0 && c < grid[0].length && grid[r][c] == 1) {
73+
result.add(new int[] {r, c});
74+
}
75+
}
76+
return result;
6577
}
6678
}

β€Žsrc/MinCostToConnectAllPoints.java

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// https://leetcode.com/problems/min-cost-to-connect-all-points
2+
// P = |points|, E = P^2
3+
// T: O(E logE + E al(P)) al = inverse Ackerman function
4+
// S: O(P + E) = S(E)
5+
6+
import java.util.ArrayList;
7+
import java.util.Comparator;
8+
import java.util.List;
9+
10+
public class MinCostToConnectAllPoints {
11+
private static class DisjointSet {
12+
private final int[] roots, rank;
13+
14+
DisjointSet(int size) {
15+
roots = new int[size];
16+
rank = new int[size];
17+
for (int i = 0 ; i < size ; i++) {
18+
roots[i] = i;
19+
rank[i] = i;
20+
}
21+
}
22+
23+
public int find(int num) {
24+
if (num == roots[num]) {
25+
return num;
26+
}
27+
return roots[num] = find(roots[num]);
28+
}
29+
30+
public boolean areConnected(int x, int y) {
31+
return find(x) == find(y);
32+
}
33+
34+
public void union(int x, int y) {
35+
final int rootX = find(x), rootY = find(y);
36+
if (rootX == rootY) {
37+
return;
38+
}
39+
if (rank[rootX] > rank[rootY]) {
40+
roots[rootY] = rootX;
41+
} else if (rank[rootX] < rank[rootY]) {
42+
roots[rootX] = rootY;
43+
} else {
44+
roots[rootY] = rootX;
45+
rank[rootX]++;
46+
}
47+
}
48+
}
49+
50+
// Kruskal's algorithm
51+
public int minCostConnectPoints(int[][] points) {
52+
final List<int[]> edges = createEdges(points);
53+
final DisjointSet disjointSet = new DisjointSet(points.length);
54+
edges.sort(Comparator.comparingInt(a -> a[2]));
55+
56+
int minCost = 0;
57+
58+
for (int[] edge : edges) {
59+
final int from = edge[0], to = edge[1], weight = edge[2];
60+
if (!disjointSet.areConnected(from, to)) {
61+
disjointSet.union(from, to);
62+
minCost += weight;
63+
}
64+
}
65+
66+
return minCost;
67+
}
68+
69+
private static List<int[]> createEdges(int[][] points) {
70+
final List<int[]> edges = new ArrayList<>();
71+
for (int i = 0 ; i < points.length ; i++) {
72+
for (int j = i + 1 ; j < points.length ; j++) {
73+
edges.add(new int[] { i, j, manhattanDistance(points[i], points[j]) });
74+
}
75+
}
76+
return edges;
77+
}
78+
79+
private static int manhattanDistance(int[] p1, int[] p2) {
80+
return Math.abs(p1[0] - p2[0]) + Math.abs(p1[1] - p2[1]);
81+
}
82+
}

0 commit comments

Comments
(0)

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /