using System.Collections.Generic;
static void Main(string[] args)
int[,] matrix = new int[,] {{ 1, 0, 0, 1, 0 },
foreach (var size in RiverSizes(matrix))
Console.Write(size + " ");
public static List<int> RiverSizes(int[,] matrix)
List<int> sizes = new List<int>();
bool[,] visited = new bool[matrix.GetLength(0), matrix.GetLength(1)];
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = 0; j < matrix.GetLength(1); j++)
int currentRiverSize = 0;
Stack<int[]> nodesToExplore = new Stack<int[]>();
nodesToExplore.Push(new int[] { i, j });
while (nodesToExplore.Count != 0)
int[] currentNode = nodesToExplore.Pop();
List<int[]> unvisitedNeighbors = new List<int[]>();
if (i > 0 && !visited[i - 1, j])
unvisitedNeighbors.Add(new int[] { i - 1, j });
if (i < matrix.GetLength(0) - 1 && !visited[i + 1, j])
unvisitedNeighbors.Add(new int[] { i + 1, j });
if (j > 0 && !visited[i, j - 1])
unvisitedNeighbors.Add(new int[] { i, j - 1 });
if (j < matrix.GetLength(1) - 1 && !visited[i, j + 1])
unvisitedNeighbors.Add(new int[] { i, j + 1 });
foreach (var neighbor in unvisitedNeighbors)
nodesToExplore.Push(neighbor);
if ((currentRiverSize > 0) && (!sizes.Contains(currentRiverSize)))
sizes.Add(currentRiverSize);