0

I am given a matrix of 0 and 1's and have to find the islands formed by one's. If found a reference :

https://www.careercup.com/question?id=14948781

About who to compute the number of island but don't know at all how to adapt the algorithm to at the end obtain the list of islands given a lists of cells of the matrix belonging to them.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
11house
  • 77
  • 7

1 Answers1

0

This problem is essentially asking you to find the connected components of an undirected graph. Here, a connected component is a group of 1's surrounded by 0s and none of the 1s in the group are connected to another separate group of 1s surrounded by 0s.

To solve this, you can start by performing a Depth First Search (DFS) on each of the elements in the 2D matrix.

  1. If the algorithm encounters an unvisited 1, increment the count of the islands
  2. Recursively perform a DFS on all the adjacent vertices (up, down, left, right)
  3. Keep track of the visited 1s so that they are not visited again (can be done using a set or by marking the node in the graph visited with a boolean flag)
  4. As soon as a 0 is found during this recursive DFS, stop the DFS
  5. Continue the algorithm by moving onto the next element in the 2D matrix and repeat steps 1-4
  6. When you reach the end of the 2D matrix return the count of islands
anaidu
  • 1