Skip to content

Commit ca867c1

Browse files
committed
Added flood fill to Matrix
1 parent 18377e2 commit ca867c1

File tree

1 file changed

+36
-4
lines changed
  • src/main/java/org/togetherjava/aoc/core/math/matrix

1 file changed

+36
-4
lines changed

src/main/java/org/togetherjava/aoc/core/math/matrix/Matrix.java

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
package org.togetherjava.aoc.core.math.matrix;
22

33

4+
import org.togetherjava.aoc.core.math.Direction;
45
import org.togetherjava.aoc.core.utils.AocUtils;
56

6-
import java.util.Arrays;
7-
import java.util.Iterator;
8-
import java.util.List;
9-
import java.util.Objects;
7+
import java.util.*;
108
import java.util.stream.IntStream;
119
import java.util.stream.Stream;
1210

@@ -262,4 +260,38 @@ public Stream<Entry<T>> stream() {
262260
public List<Entry<T>> getEntries() {
263261
return stream().toList();
264262
}
263+
264+
public List<Entry<T>> groupElements(MatrixPosition position) {
265+
if (outOfBounds(position.row(), position.col())) {
266+
throw new IndexOutOfBoundsException("Starting coordinates [%d, %d] are out of bounds.".formatted(position.row(), position.col()));
267+
}
268+
269+
T initialValue = get(position); // Get the starting value
270+
List<Entry<T>> groupedCells = new ArrayList<>();
271+
Queue<MatrixPosition> queue = new LinkedList<>();
272+
boolean[][] visited = new boolean[rows][cols];
273+
274+
queue.add(position);
275+
276+
while (!queue.isEmpty()) {
277+
MatrixPosition current = queue.poll();
278+
int row = current.row();
279+
int col = current.col();
280+
281+
if (outOfBounds(row, col) || visited[row][col] || !Objects.equals(get(row, col), initialValue)) {
282+
continue;
283+
}
284+
285+
// Mark as visited and add to the result list
286+
visited[row][col] = true;
287+
groupedCells.add(new Entry<>(row, col, initialValue));
288+
289+
// Add neighbors to the queue
290+
queue.add(current.move(Direction.NORTH));
291+
queue.add(current.move(Direction.SOUTH));
292+
queue.add(current.move(Direction.WEST));
293+
queue.add(current.move(Direction.EAST));
294+
}
295+
return groupedCells;
296+
}
265297
}

0 commit comments

Comments
 (0)