← Meta (Facebook) bank

Meta (Facebook) · Question 58 · Graphs

Number of Islands

GraphsPythoncode⏱ O(mn)💾 O(mn)
Product-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. 2Sink flooded cells to water.

Sample input / output

Input:
4 5
11000
11000
00100
00011
Output:
3

Constraints

1 <= m, n <= 300; cells '0'/'1'; DFS recursion depth fits.

Solution — read it, then walk it

Time O(mn)Space O(mn)Loops 2Branches 3Returns 2source · Python
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeatyes↻ repeat↻ repeatyesnoSTARTgridDEFINE dfs(i, j)if i < 0 or i >=len(grid) or j < 0 orj >= len(grid[0]) o…RETURNgrid[i][j] = '0'dfs(i + 1, j)dfs(i - 1, j)dfs(i, j + 1)dfs(i, j - 1)count = 0for i inrange(len(grid))for j inrange(len(grid[0]))if grid[i][j] == '1'count += 1dfs(i, j)RETURN countDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)m = int(next(it)); n =int(next(it))grid = [[c for c innext(it)] for _ inrange(m)]print(numIslands(grid))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/26

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