Home › Company-wise questions › L&T Mindtree › Number of Islands ← L&T Mindtree bank
L&T Mindtree · Question 58 · Graphs
Number of Islands Graphs Java 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 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 Each fresh '1' starts a new island flood. 2 DFS sinks flooded cells to water. Sample input / output Input:
grid = 4x5 with 3 islands
Output:
3 Constraints 1 <= m, n <= 300; cells '0'/'1'.
Solution — read it, then walk it Flowchart Pseudocode
Time O(mn)Space O(mn)Loops 2Branches 2Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
↻ repeat yes ↻ repeat ↻ repeat START import java.util.* DEFINE class Main DEFINE static int numIslands(char[][] grid) DEFINE count = 0 for (int i = 0; i < grid.length; i++) for (int j = 0; j < grid[0].length; j++) if (grid[i][j] == '1') count++ dfs(grid, i, j) RETURN count DEFINE static void dfs(char[][] grid, int i, int j) if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length |… grid[i][j] = '0' dfs(grid, i + 1, j) dfs(grid, i - 1, j) dfs(grid, i, j + 1) dfs(grid, i, j - 1) DEFINE static void main(String[] args) DEFINE [][] grid = {{'1','1','0','0','0'},{'1','1','0','0','0'}, {'0','0','1','0','0'},{'0','0','0','1','1'}} System.out.println(numIslands(grid)) END start / end statement condition loop returns definition← Q57 · Serialize and Deserialize Binary Tree Q59 · Clone Graph → Solution code Core logic highlighted in green
Language Python Javasource C++ 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 →