Count number of freshwater lakes in 2d Matrix
Anonymous User
7743

Given an input matrix like this

private static int[][] input =
{{0,0,1,0,0,0,0,1,0,0,0,0,0}, // 0 ... 0
{0,0,0,0,0,0,0,1,1,1,0,0,0}, // 0 ... 0
{0,1,1,1,1,0,0,0,0,0,0,0,0},
{0,1,0,0,1,1,0,0,1,1,1,0,0},
{0,1,0,1,1,1,0,0,1,1,1,0,0},
{0,0,1,0,0,0,0,0,1,0,1,0,0},
{0,0,0,0,0,0,0,1,1,1,0,0,0},
{0,0,0,0,0,0,0,1,1,0,0,0,0}};

Here 0 indidates water and its value can be either saltwater or freshwater
1 is land

the input matrix is implicitly surrounded by an infinite ocean as shown in the comments part in the first and second row.

Here the condition is water moves vertically and horizontally (up down left right) but not diagonally

Write a method which takes this input matrix and return the total number of freshwater lakes. For the above matrix there are two freshwater island.

How do i solve this one? I tried to solve it using DFS bottom up but couldn't complete it.

Comments (19)