Mid From PDF Coding C# Coding Interview

Find Number of Islands in 2D Matrix?

int NumIslands(char[][] grid)
{
if (grid == null || grid.Length == 0) return 0;
int count = 0;
for (int i = 0; i < grid.Length; i++)
{
for (int j = 0; j < grid[0].Length; j++)
{
if (grid[i][j] == '1')

Follow on:

{

DFS(grid, i, j);

count++;

}
}
}
return count;
}

void DFS(char[][] grid, int i, int j)

{
if (i < 0 || j < 0 || i >= grid.Length || j >= grid[0].Length ||

grid[i][j] == '0')

return;
grid[i][j] = '0'; // Mark visited

DFS(grid, i + 1, j);

DFS(grid, i - 1, j);

DFS(grid, i, j + 1);

DFS(grid, i, j - 1);

}

Explanation:

Use DFS to mark all connected land cells, count islands by visiting unvisited lands.

More from C# Programming Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details