Skip to content
Snippets Groups Projects
Verified Commit b276dd6d authored by Dmytro Bogatov's avatar Dmytro Bogatov :two_hearts:
Browse files

Add count the islands problem.

parent 2894ec42
Branches
No related tags found
No related merge requests found
namespace CodingInterview.HackerRank
{
/// <summary>
/// Given a boolean matrix, find the number of islands.
///
/// What is an island?
///
/// A group of connected 1s forms an island.
/// For example, the below matrix contains 5 islands:
///
/// {1, 1, 0, 0, 0},
/// {0, 1, 0, 0, 1},
/// {1, 0, 0, 1, 1},
/// {0, 0, 0, 0, 0},
/// {1, 0, 1, 0, 1}
/// </summary>
public class CountTheIslands
{
static int[,] map;
/// <summary>
/// Returns the number of islands
/// </summary>
/// <param name="map">the map matrix</param>
/// <returns>the number of islands</returns>
public int Solve(int[,] map)
{
CountTheIslands.map = map;
var islands = 0;
for (var i = 0; i < map.GetLength(0); i++)
{
for (var j = 0; j < map.GetLength(1); j++)
{
if (DFS(i, j))
{
islands++;
}
}
}
return islands;
}
static bool DFS(int i, int j)
{
if (i < 0 || i == map.GetLength(0) || j < 0 || j == map.GetLength(1) || map[i, j] == 0 || map[i, j] == 2)
{
return false;
}
map[i, j] = 2;
DFS(i, j + 1); // right
DFS(i + 1, j + 1); // right down
DFS(i + 1, j); // down
DFS(i + 1, j - 1); // left down
DFS(i, j - 1); // left
DFS(i - 1, j - 1); // left up
DFS(i - 1, j); // up
DFS(i - 1, j + 1); // right up
return true;
}
}
}
using Xunit;
namespace CodingInterview.Tests.HackerRank
{
public class CountTheIslands
{
[Fact]
public void TestCases()
{
// From Hacker Rank
Assert.Equal(
5,
new CodingInterview.HackerRank.CountTheIslands().Solve(
new int[,] {
{1, 1, 0, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 0, 1, 1},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 1}
}
)
);
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment