using System.Collections.Generic;
public static void Main()
var data = new int [5, 5] {
var solution = new Solution();
var answers = solution.GetRiverSizes(data);
foreach (var answer in answers)
Console.Write(string.Format("{0}, ", answer));
public int[] GetRiverSizes(int[,] matrix)
var riverSizes = new List<int>();
var visited = new bool[matrix.GetUpperBound(0) + 1, matrix.GetUpperBound(1) + 1];
for (var i = 0; i <= matrix.GetUpperBound(0); i++)
for (var j = 0; j <= matrix.GetUpperBound(1); j++)
BFSHelper(i, j, matrix, visited, riverSizes);
return riverSizes.ToArray();
public void BFSHelper(int startRow, int startCol, int[,] matrix, bool[,] visited, List<int> riverSizes) {
var queue = new Queue<Node>();
queue.Enqueue(new Node { rowIndex = startRow, colIndex = startCol });
var current = queue.Dequeue();
if (!visited[current.rowIndex, current.colIndex])
visited[current.rowIndex, current.colIndex] = true;
if (matrix[current.rowIndex, current.colIndex] == 1)
if (current.rowIndex - 1 >= 0)
queue.Enqueue(new Node { rowIndex = current.rowIndex - 1, colIndex = current.colIndex });
if (current.colIndex + 1 <= matrix.GetUpperBound(1))
queue.Enqueue(new Node { rowIndex = current.rowIndex, colIndex = current.colIndex + 1 });
if (current.rowIndex + 1 <= matrix.GetUpperBound(0))
queue.Enqueue(new Node { rowIndex = current.rowIndex + 1, colIndex = current.colIndex });
if (current.colIndex - 1 >= 0){
queue.Enqueue(new Node { rowIndex = current.rowIndex, colIndex = current.colIndex - 1 });
if (riverSize > 0) riverSizes.Add(riverSize);
public int rowIndex { get; set; }
public int colIndex { get; set; }