Last active
March 13, 2024 19:32
-
-
Save lesnitsky/f332296b3b618763c0f59e883840d2d5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final visited = <(int, int)>{}; | |
Iterable<List<(int, int)>> getBiomes(List<List<int>> worldmap) sync* { | |
visited.clear(); | |
for (int i = 0; i < worldmap.length; i++) { | |
for (int j = 0; j < worldmap[i].length; j++) { | |
if (visited.contains((i, j))) { | |
continue; | |
} | |
yield traverse(worldmap, [(i, j)]); | |
} | |
} | |
} | |
List<(int, int)> traverse( | |
List<List<int>> matrix, | |
List<(int, int)> biome, | |
) { | |
final last = biome.last; | |
final (x, y) = last; | |
visited.add((x, y)); | |
if (x < 0 || x >= matrix.length || y < 0 || y >= matrix[x].length) { | |
return biome; | |
} | |
final current = matrix[x][y]; | |
// top | |
if (x > 0 && matrix[x - 1][y] == current && !visited.contains((x - 1, y))) { | |
biome.add((x - 1, y)); | |
traverse(matrix, biome); | |
} | |
// right | |
if (y < matrix[x].length - 1 && | |
matrix[x][y + 1] == current && | |
!visited.contains((x, y + 1))) { | |
biome.add((x, y + 1)); | |
traverse(matrix, biome); | |
} | |
// bottom | |
if (x < matrix.length - 1 && | |
matrix[x + 1][y] == current && | |
!visited.contains((x + 1, y))) { | |
biome.add((x + 1, y)); | |
traverse(matrix, biome); | |
} | |
// left | |
if (y > 0 && matrix[x][y - 1] == current && !visited.contains((x, y - 1))) { | |
biome.add((x, y - 1)); | |
traverse(matrix, biome); | |
} | |
return biome; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment