← Google bank

Google · Question 63 · Graphs

Number of Islands (DFS)

GraphsPythoncode⏱ O(rows*cols)💾 O(rows*cols)
Product-based

Problem

Count the number of islands ( connected groups of '1's) in a 2D grid using DFS.

Approach

Perform DFS to mark connected land as visited.

Time O(rows*cols)Space O(rows*cols)

How it works

  1. 1Traverse the grid and call DFS on unvisited land.
  2. 2DFS visits and marks all connected land cells.
  3. 3Increment the island count per DFS call.
  4. 4Return the total islands.

Sample input / output

Input:
4 5
11000
11000
00100
00011
Output:
3

Constraints

m == grid.length; n == grid[i].length; 1 <= m, n <= 300; cells are '0' or '1'.

Solution — read it, then walk it

Time O(rows*cols)Space O(rows*cols)Loops 2Branches 4Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesno↻ repeatyes↻ repeat↻ repeatyesnoSTARTgridif not gridRETURN 0rows, cols = len(grid),len(grid[0])visited = set()count = 0DEFINE dfs(r, c)if (r < 0 or r >= rowsor c < 0 or c >= colsorgrid[r][c] == '0' or (r, c)in visited)RETURNvisited.add((r, c))dfs(r + 1, c)dfs(r - 1, c)dfs(r, c + 1)dfs(r, c - 1)for r in range(rows)for c in range(cols)if grid[r][c] == '1'and (r, c) not invisiteddfs(r, c)count += 1RETURN 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/31

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