Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to count number of surrounded islands in the matrix in python
In this problem, we have a binary matrix where 1 represents land and 0 represents water. An island is a group of connected 1s, and we need to find islands that are completely surrounded by water (not touching the matrix boundaries).
So, if the input matrix is like:
The output will be 2, as there are three islands, but only two of them are completely surrounded by water.
Algorithm
The approach uses Depth-First Search (DFS) to check if an island is completely surrounded ?
- For each land cell (1), start a DFS traversal
- During DFS, mark visited cells as 0 to avoid revisiting
- If DFS reaches a boundary, the island is not completely surrounded
- If DFS completes without reaching boundaries, the island is surrounded
Implementation
class Solution:
def solve(self, matrix):
def dfs(i, j):
# Check if we've reached matrix boundaries
if i < 0 or j < 0 or i >= R or j >= C:
return False
# If current cell is water, continue
if matrix[i][j] == 0:
return True
# Mark current cell as visited (convert to water)
matrix[i][j] = 0
# Check all four directions
a = dfs(i + 1, j) # down
b = dfs(i - 1, j) # up
c = dfs(i, j + 1) # right
d = dfs(i, j - 1) # left
# Island is surrounded only if all directions are surrounded
return a and b and c and d
R, C = len(matrix), len(matrix[0])
ans = 0
# Iterate through each cell in the matrix
for i in range(R):
for j in range(C):
if matrix[i][j] == 1:
# If DFS returns True, island is completely surrounded
if dfs(i, j):
ans += 1
return ans
# Test the solution
ob = Solution()
matrix = [
[1, 0, 0, 0, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]
]
print("Number of surrounded islands:", ob.solve(matrix))
Number of surrounded islands: 2
How It Works
The DFS function works as follows ?
- Base case: If we reach matrix boundaries, return False (island touches edge)
- Water cell: If current cell is 0 (water), return True (valid boundary)
- Land cell: Mark as visited (set to 0) and recursively check all 4 directions
- Result: Return True only if ALL directions are completely surrounded
Key Points
- Islands touching matrix boundaries are not considered surrounded
- The algorithm modifies the original matrix by marking visited cells as 0
- Time complexity: O(R × C) where R and C are matrix dimensions
- Space complexity: O(R × C) for recursion stack in worst case
Conclusion
This solution uses DFS to identify completely surrounded islands by checking if any land cell connects to matrix boundaries. An island is surrounded only when all its cells are enclosed by water without touching the edges.
