Leet code 200 : number-of-islands in C#-
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] is '0' or '1'.
Leetcode Qn :
Example 1:
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
Example 2:
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
Leetcode Qn :
public int NumIslands(char[][] grid) {
if (grid == null || grid.Length == 0 || grid[0].Length == 0) {
return 0;
}
int numIslands = 0;
int rows = grid.Length;
int cols = grid[0].Length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == '1') {
numIslands++;
dfs(grid, i, j);
}
}
}
return numIslands;
}
private void dfs(char[][] grid, int i, int j) {
int rows = grid.Length;
int cols = grid[0].Length;
if (i < 0 || i >= rows || j < 0 || j >= cols || grid[i][j] == '0') {
return;
}
grid[i][j] = '0'; // Mark as visited
// Check adjacent cells
dfs(grid, i - 1, j); // up
dfs(grid, i + 1, j); // down
dfs(grid, i, j - 1); // left
dfs(grid, i, j + 1); // right
}
This method takes a 2D grid of characters as input and returns the number of islands. Islands are groups of adjacent '1's, where adjacency is defined vertically or horizontally (not diagonally).
The algorithm iterates through each cell in the grid. When it finds a '1', it increments the count of islands and performs a depth-first search to mark all connected '1's as visited. Once all connected '1's are visited, it moves on to the next cell. This process continues until all cells are visited. The count of islands is then returned.
Comments
Post a Comment