{"id":"6b093ddfbd4755deb67ee08c","slug":"number-of-islands","title":"Number of islands","summary":"Count connected land areas on a map made of a character grid. Graph search (BFS/DFS) over cells – and the trap of deep recursion on a large map.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"medium","topics":[],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["graphs","bfs","dfs","matrix","flood-fill","union-find"],"languages":[{"lang":"typescript","runner":"browser","starter":"/** Number of 4-directionally connected groups of '1' cells. */\nfunction countIslands(grid: string[]): number {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":8,"tests":"test('one big island', () => {\n  expect(countIslands(['11110', '11010', '11000', '00000'])).toBe(1);\n});\n\ntest('several islands', () => {\n  expect(countIslands(['11000', '11000', '00100', '00011'])).toBe(3);\n});\n\ntest('diagonals do not connect', () => {\n  expect(countIslands(['101', '010', '101'])).toBe(5);\n});\n\ntest('a ring with an islet inside', () => {\n  expect(countIslands(['11111', '10001', '10101', '10001', '11111'])).toBe(2);\n});\n\ntest('empty grids and water only', () => {\n  expect(countIslands([])).toBe(0);\n  expect(countIslands([''])).toBe(0);\n  expect(countIslands(['000', '000'])).toBe(0);\n});\n\ntest('single cells and single rows', () => {\n  expect(countIslands(['1'])).toBe(1);\n  expect(countIslands(['1011101'])).toBe(3);\n  expect(countIslands(['1', '1', '0', '1'])).toBe(2);\n});\n\ntest('a winding snake is one island', () => {\n  expect(countIslands(['11111', '00001', '11111', '10000', '11111'])).toBe(1);\n});\n\ntest('performance: 300 × 300 all land and a checkerboard', () => {\n  const n = 300;\n  const land = Array.from({ length: n }, () => '1'.repeat(n));\n  expect(countIslands(land)).toBe(1);\n  const board = Array.from({ length: n }, (_, r) => (r % 2 ? '01' : '10').repeat(n / 2));\n  expect(countIslands(board)).toBe((n * n) / 2);\n});\n"},{"lang":"javascript","runner":"browser","starter":"/**\n * Number of 4-directionally connected groups of '1' cells.\n * @param {string[]} grid rows of '0'/'1'\n * @returns {number}\n */\nfunction countIslands(grid) {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":8,"tests":"test('one big island', () => {\n  expect(countIslands(['11110', '11010', '11000', '00000'])).toBe(1);\n});\n\ntest('several islands', () => {\n  expect(countIslands(['11000', '11000', '00100', '00011'])).toBe(3);\n});\n\ntest('diagonals do not connect', () => {\n  expect(countIslands(['101', '010', '101'])).toBe(5);\n});\n\ntest('a ring with an islet inside', () => {\n  expect(countIslands(['11111', '10001', '10101', '10001', '11111'])).toBe(2);\n});\n\ntest('empty grids and water only', () => {\n  expect(countIslands([])).toBe(0);\n  expect(countIslands([''])).toBe(0);\n  expect(countIslands(['000', '000'])).toBe(0);\n});\n\ntest('single cells and single rows', () => {\n  expect(countIslands(['1'])).toBe(1);\n  expect(countIslands(['1011101'])).toBe(3);\n  expect(countIslands(['1', '1', '0', '1'])).toBe(2);\n});\n\ntest('a winding snake is one island', () => {\n  expect(countIslands(['11111', '00001', '11111', '10000', '11111'])).toBe(1);\n});\n\ntest('performance: 300 × 300 all land and a checkerboard', () => {\n  const n = 300;\n  const land = Array.from({ length: n }, () => '1'.repeat(n));\n  expect(countIslands(land)).toBe(1);\n  const board = Array.from({ length: n }, (_, r) => (r % 2 ? '01' : '10').repeat(n / 2));\n  expect(countIslands(board)).toBe((n * n) / 2);\n});\n"},{"lang":"python","runner":"browser","starter":"def count_islands(grid: list[str]) -> int:\n    \"\"\"Number of 4-directionally connected groups of '1' cells.\"\"\"\n    raise NotImplementedError\n","testCount":8,"tests":"def check(grid, expected):\n    got = count_islands(grid)\n    assert got == expected, f\"count_islands({grid[:5]}): expected {expected}, got {got}\"\n\n\ndef test_one_big_island():\n    check([\"11110\", \"11010\", \"11000\", \"00000\"], 1)\n\n\ndef test_several_islands():\n    check([\"11000\", \"11000\", \"00100\", \"00011\"], 3)\n\n\ndef test_diagonals_do_not_connect():\n    check([\"101\", \"010\", \"101\"], 5)\n\n\ndef test_ring_with_an_islet_inside():\n    check([\"11111\", \"10001\", \"10101\", \"10001\", \"11111\"], 2)\n\n\ndef test_empty_grids_and_water_only():\n    check([], 0)\n    check([\"\"], 0)\n    check([\"000\", \"000\"], 0)\n\n\ndef test_single_cells_and_single_rows():\n    check([\"1\"], 1)\n    check([\"1011101\"], 3)\n    check([\"1\", \"1\", \"0\", \"1\"], 2)\n\n\ndef test_winding_snake_is_one_island():\n    check([\"11111\", \"00001\", \"11111\", \"10000\", \"11111\"], 1)\n\n\ndef test_performance_300x300():\n    n = 300\n    check([\"1\" * n] * n, 1)\n    board = [(\"01\" if r % 2 else \"10\") * (n // 2) for r in range(n)]\n    check(board, n * n // 2)\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\n\npublic static class Solution\n{\n    /// <summary>Number of 4-directionally connected groups of '1' cells.</summary>\n    public static int CountIslands(string[] grid)\n    {\n        throw new NotImplementedException();\n    }\n}\n","testCount":8},{"lang":"java","runner":"judge0","starter":"class Solution {\n    /** Number of 4-directionally connected groups of '1' cells. */\n    static int countIslands(String[] grid) {\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n","testCount":8},{"lang":"go","runner":"judge0","starter":"package main\n\n// CountIslands returns the number of 4-directionally connected groups of '1' cells.\nfunc CountIslands(grid []string) int {\n\tpanic(\"not implemented\")\n}\n","testCount":8}],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:55.102Z","requestedLang":"en","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"A drone map is a grid of cells: "},{"type":"text","text":"'1'","marks":[{"type":"code"}]},{"type":"text","text":" is land, "},{"type":"text","text":"'0'","marks":[{"type":"code"}]},{"type":"text","text":" is water. An "},{"type":"text","text":"island","marks":[{"type":"bold"}]},{"type":"text","text":" is a maximal land area in which every cell can reach every other one by moving up, down, left and right (diagonals do not count). How many islands are on the map?"}]},{"type":"heading","attrs":{"level":2,"id":"task"},"content":[{"type":"text","text":"Task"}]},{"type":"paragraph","content":[{"type":"text","text":"The function gets the grid as a list of equally long strings (each string is a row) and returns the number of islands. The input must not be modified (strings are immutable anyway – you need your own visited array)."}]},{"type":"paragraph","content":[{"type":"text","text":"Signatures: "},{"type":"text","text":"countIslands(grid)","marks":[{"type":"code"}]},{"type":"text","text":" (JS/TS), "},{"type":"text","text":"count_islands(grid)","marks":[{"type":"code"}]},{"type":"text","text":" (Python), "},{"type":"text","text":"Solution.CountIslands","marks":[{"type":"code"}]},{"type":"text","text":" (C#, "},{"type":"text","text":"string[]","marks":[{"type":"code"}]},{"type":"text","text":"), "},{"type":"text","text":"Solution.countIslands","marks":[{"type":"code"}]},{"type":"text","text":" (Java, "},{"type":"text","text":"String[]","marks":[{"type":"code"}]},{"type":"text","text":"), "},{"type":"text","text":"CountIslands","marks":[{"type":"code"}]},{"type":"text","text":" (Go, "},{"type":"text","text":"[]string","marks":[{"type":"code"}]},{"type":"text","text":")."}]},{"type":"heading","attrs":{"level":2,"id":"examples"},"content":[{"type":"text","text":"Examples"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Grid"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Result"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[\"11110\", \"11010\", \"11000\", \"00000\"]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"1","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[\"11000\", \"11000\", \"00100\", \"00011\"]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"3","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[\"101\", \"010\", \"101\"]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"5","marks":[{"type":"code"}]},{"type":"text","text":" – diagonals do not connect"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[\"11111\", \"10001\", \"10101\", \"10001\", \"11111\"]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"2","marks":[{"type":"code"}]},{"type":"text","text":" – a ring and an islet inside"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"0","marks":[{"type":"code"}]}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"constraints"},"content":[{"type":"text","text":"Constraints"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"0 ≤ rows, columns ≤ 300","marks":[{"type":"code"}]},{"type":"text","text":" (up to 90,000 cells)."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"One island may cover the whole map – a recursive DFS then goes tens of thousands of calls deep."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"expected-complexity"},"content":[{"type":"text","text":"Expected complexity"}]},{"type":"paragraph","content":[{"type":"text","text":"O(R · C)","marks":[{"type":"bold"}]},{"type":"text","text":" time, "},{"type":"text","text":"O(R · C)","marks":[{"type":"bold"}]},{"type":"text","text":" memory for the visited array and the queue/stack."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[{"provider":"leetcode","url":"https://leetcode.com/problems/number-of-islands/","title":"LeetCode 200 – Number of Islands","difficulty":null}],"articles":[],"topicsInfo":[],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:55.103Z","updatedAt":"2026-11-27T08:22:55.103Z"}