← L&T Mindtree bank

L&T Mindtree · Question 58 · Graphs

Number of Islands

GraphsJavacode⏱ O(mn)💾 O(mn)
Service-based

Problem

You are given 2D grid of '1's (land) and '0's (water). Count number of islands.

Approach

Flood each fresh land cell with DFS, sinking it so it never recounts.

Time O(mn)Space O(mn)

How it works

  1. 1Each fresh '1' starts a new island flood.
  2. 2DFS sinks flooded cells to water.

Sample input / output

Input:
grid = 4x5 with 3 islands
Output:
3

Constraints

1 <= m, n <= 300; cells '0'/'1'.

Solution — read it, then walk it

Time O(mn)Space O(mn)Loops 2Branches 2Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyes↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static intnumIslands(char[][] grid)DEFINE count = 0for (int i = 0; i <grid.length; i++)for (int j = 0; j <grid[0].length; j++)if (grid[i][j] == '1')count++dfs(grid, i, j)RETURN countDEFINE static voiddfs(char[][] grid, int i,int j)if (i < 0 || j < 0 ||i >= grid.length || j>= grid[0].length |…grid[i][j] = '0'dfs(grid, i + 1, j)dfs(grid, i - 1, j)dfs(grid, i, j + 1)dfs(grid, i, j - 1)DEFINE static voidmain(String[] args)DEFINE [][] grid ={{'1','1','0','0','0'},{'1','1','0','0','0'},{'0','0','1','0','0'},{'0','0','0','1','1'}}System.out.println(numIslands(grid))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/22

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits