← Google bank

Google · Question 50 · Graphs

Number of Islands (BFS)

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

Problem

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

Approach

Use BFS to traverse each island and mark visited.

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

How it works

  1. 1Iterate all cells, start BFS on unvisited land.
  2. 2BFS visits all connected land cells, marking them visited.
  3. 3Increment the island count for each BFS.
  4. 4Return the total islands.

Sample input / output

Input:
4 5
11110
11010
11000
00000
Output:
1

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 4Branches 5Returns 2source · Python
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeatyes↻ repeatyes↻ repeat↻ repeat↻ repeatyes↻ repeat↻ repeatyesnoSTARTfrom collections importdequeDEFINE numIslands(grid)if not gridRETURN 0rows, cols = len(grid),len(grid[0])visited = set()islands = 0DEFINE bfs(r, c)queue = deque([(r, c)])visited.add((r, c))while queuerow, col = queue.popleft()for nr, nc in [(row -1, col), (row + 1,col), (row, col - 1)…if 0 <= nr < rows and0 <= nc < colsif grid[nr][nc] == "1"and (nr, nc) not invisitedvisited.add((nr, nc))queue.append((nr, nc))for r in range(rows)for c in range(cols)if grid[r][c] == "1"and (r, c) not invisitedbfs(r, c)islands += 1RETURN islandsDEFINE 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/33

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