Home › Company-wise questions › Infosys › Number of Islands ← Infosys bank
Infosys · Question 69 · Graphs
Number of Islands Graphs C++ code ⏱ O(mn) 💾 O(mn)
Service-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
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 Each fresh '1' starts a flood. 2 DFS 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 Flowchart Pseudocode
Time O(mn)Space O(mn)Loops 2Branches 2Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
↻ repeat yes ↻ repeat ↻ repeat START using namespace std CLASS Solution DEFINE DEFINE dfs(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'; // mark visited dfs(grid, r + 1, c) dfs(grid, r - 1, c) dfs(grid, r, c + 1) dfs(grid, r, c - 1) DEFINE numIslands(vector<vector<char>>& grid) DEFINE count = 0 for (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 count DEFINE main() Solution sol vector<vector<char>> grid = {{'1','1','0','0','0'},{'1','1','0','0','0'}, cout << sol.numIslands(grid) << endl RETURN 0 END start / end statement condition loop returns definition← Q67 · Word Break Q70 · Pacific Atlantic Water Flow → Solution code Core logic highlighted in green
Language Python Java C++source C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →