private void BuildTheForest(int[,] grid, MyGraph <Coordinates> graph) { for (int i = 0; i < grid.GetLength(0); i++) { for (int j = 0; j < grid.GetLength(1); j++) { if (grid[i, j] == 1) { var tempCoordinates = new Coordinates(i, j); if (!graph.Contains(tempCoordinates)) { graph.AddNode(tempCoordinates); } if (GetValidValue(grid, i + 1, j) == 1) { var otherCoordinates = new Coordinates(i + 1, j); if (!graph.Contains(otherCoordinates)) { graph.AddNode(otherCoordinates); } graph.AddUndirectedEdge(graph.Nodes.FindByData(tempCoordinates), graph.Nodes.FindByData(otherCoordinates), 0); } if (GetValidValue(grid, i, j + 1) == 1) { var otherCoordinates = new Coordinates(i, j + 1); if (!graph.Contains(otherCoordinates)) { graph.AddNode(otherCoordinates); } graph.AddUndirectedEdge(graph.Nodes.FindByData(tempCoordinates), graph.Nodes.FindByData(otherCoordinates), 0); } } } } }