← Infosys bank

Infosys · Question 69 · Graphs

Number of Islands

GraphsC++code⏱ O(mn)💾 O(mn)
Service-based

Problem

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

Approach

Use DFS or BFS to traverse and mark visited.

Time O(mn)Space O(mn)

How it works

  1. 1Each fresh '1' starts a flood.
  2. 2DFS sinks the whole island to '0'.

Sample input / output

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

Constraints

1 <= m, n <= 300.

Solution — read it, then walk it

Time O(mn)Space O(mn)Loops 2Branches 2Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyes↻ repeat↻ repeatSTARTinclude <iostream>include <vector>using namespace stdCLASS SolutionDEFINEDEFINEdfs(vector<vector<char>>&grid, int r, int c)DEFINE rows = grid.size(),cols = grid[0].size()if (r < 0 || c < 0 ||r >= rows || c >= cols|| grid[r][c] == '0'…grid[r][c] = '0'; // markvisiteddfs(grid, r + 1, c)dfs(grid, r - 1, c)dfs(grid, r, c + 1)dfs(grid, r, c - 1)DEFINEnumIslands(vector<vector<char>>&grid)DEFINE count = 0for (size_t r = 0; r <grid.size(); r++)for (size_t c = 0; c <grid[0].size(); c++)if (grid[r][c] == '1')count++dfs(grid, r, c)RETURN countDEFINE main()Solution solvector<vector<char>> grid ={{'1','1','0','0','0'},{'1','1','0','0','0'},cout <<sol.numIslands(grid) <<endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/27

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