|
1 | 1 | package org.togetherjava.aoc.core.math.matrix;
|
2 | 2 |
|
3 | 3 |
|
| 4 | +import org.togetherjava.aoc.core.math.Direction; |
4 | 5 | import org.togetherjava.aoc.core.utils.AocUtils;
|
5 | 6 |
|
6 |
| -import java.util.Arrays; |
7 |
| -import java.util.Iterator; |
8 |
| -import java.util.List; |
9 |
| -import java.util.Objects; |
| 7 | +import java.util.*; |
10 | 8 | import java.util.stream.IntStream;
|
11 | 9 | import java.util.stream.Stream;
|
12 | 10 |
|
@@ -262,4 +260,38 @@ public Stream<Entry<T>> stream() {
|
262 | 260 | public List<Entry<T>> getEntries() {
|
263 | 261 | return stream().toList();
|
264 | 262 | }
|
| 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 | + } |
265 | 297 | }
|
0 commit comments