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.
- If the algorithm encounters an unvisited 1, increment the count of the islands
- Recursively perform a DFS on all the adjacent vertices (up, down, left, right)
- 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)
- As soon as a 0 is found during this recursive DFS, stop the DFS
- Continue the algorithm by moving onto the next element in the 2D matrix and
repeat steps 1-4
- When you reach the end of the 2D matrix return the count of islands