Mid
From PDF
Coding
C# Coding Interview
Find Number of Islands in 2D Matrix?
Short answer: 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.
Example code
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;
Real-world example (ShopNest)
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png