{"id":10598,"date":"2026-11-29T08:52:53","date_gmt":"2026-11-29T08:52:53","guid":{"rendered":"https:\/\/cybersecurityinfocus.com\/?p=10598"},"modified":"2026-11-29T08:52:53","modified_gmt":"2026-11-29T08:52:53","slug":"number-of-islands-in-python-bfs-and-dfs-explained","status":"publish","type":"post","link":"https:\/\/cybersecurityinfocus.com\/?p=10598","title":{"rendered":"Number of Islands in Python: BFS and DFS Explained"},"content":{"rendered":"<p class=\"wp-block-paragraph\">Given a rectangular grid of strings \u20181\u2019 (land) and \u20180\u2019 (water), return the number of connected land components. Only horizontal and vertical neighbors connect. This medium-level graph problem treats each land cell as a vertex and each valid neighbor as an edge.<\/p>\n<h2 class=\"wp-block-heading\">Example<\/h2>\n<p class=\"wp-block-paragraph\">Rows 110,010,001 contain two islands.<\/p>\n<h2 class=\"wp-block-heading\">Pattern recognition and hints<\/h2>\n<p class=\"wp-block-paragraph\"><strong>Hint 1:<\/strong> Scan every cell; water never starts an island.<\/p>\n<p class=\"wp-block-paragraph\"><strong>Hint 2:<\/strong> From an unvisited land cell, explore every reachable land neighbor.<\/p>\n<p class=\"wp-block-paragraph\"><strong>Hint 3:<\/strong> Mark cells when discovered, not after processing them. Count each new traversal once.<\/p>\n<h2 class=\"wp-block-heading\">Recursive DFS baseline<\/h2>\n<p>def dfs_count(grid):<br \/>\n    g = [row[:] for row in grid]<br \/>\n    def visit(r,c):<br \/>\n        if not (0 &lt;= r &lt; len(g) and 0 &lt;= c &lt; len(g[0])) or g[r][c] != &#8220;1&#8221;:<br \/>\n            return<br \/>\n        g[r][c] = &#8220;0&#8221;<br \/>\n        for dr,dc in ((1,0),(-1,0),(0,1),(0,-1)):<br \/>\n            visit(r+dr,c+dc)<br \/>\n    count = 0<br \/>\n    for r,row in enumerate(g):<br \/>\n        for c,v in enumerate(row):<br \/>\n            if v == &#8220;1&#8221;:<br \/>\n                count += 1<br \/>\n                visit(r,c)<br \/>\n    return count<\/p>\n<p class=\"wp-block-paragraph\">Recursive DFS is already asymptotically optimal. It copies the grid and marks visited cells as water, preserving the caller\u2019s input. Its drawback is Python\u2019s recursion depth on long connected components.<\/p>\n<h2 class=\"wp-block-heading\">Optimized or iterative approach<\/h2>\n<p class=\"wp-block-paragraph\">Every unvisited land cell starts a new traversal; mark the entire connected component.<\/p>\n<p>from collections import deque<br \/>\ndef num_islands(grid):<br \/>\n    if not grid or not grid[0]:<br \/>\n        return 0<br \/>\n    rows, cols = len(grid), len(grid[0])<br \/>\n    seen = set()<br \/>\n    count = 0<br \/>\n    for r in range(rows):<br \/>\n        for c in range(cols):<br \/>\n            if grid[r][c] != &#8220;1&#8221; or (r,c) in seen:<br \/>\n                continue<br \/>\n            count += 1<br \/>\n            seen.add((r,c))<br \/>\n            q = deque([(r,c)])<br \/>\n            while q:<br \/>\n                x,y = q.popleft()<br \/>\n                for dx,dy in ((1,0),(-1,0),(0,1),(0,-1)):<br \/>\n                    a,b = x+dx,y+dy<br \/>\n                    if (0 &lt;= a &lt; rows and 0 &lt;= b &lt; cols<br \/>\n                        and grid[a][b] == &#8220;1&#8221; and (a,b) not in seen):<br \/>\n                        seen.add((a,b))<br \/>\n                        q.append((a,b))<br \/>\n    return count<\/p>\n<h2 class=\"wp-block-heading\">Pseudocode<\/h2>\n<p>SET count = 0 and seen = empty set<br \/>\nFOR each cell:<br \/>\n  IF land and not seen:<br \/>\n    INCREMENT count<br \/>\n    MARK cell and enqueue it<br \/>\n    WHILE queue is not empty:<br \/>\n      DEQUEUE cell<br \/>\n      FOR each of its four neighbors:<br \/>\n        IF valid unvisited land:<br \/>\n          MARK neighbor and enqueue it<br \/>\nRETURN count<\/p>\n<h2 class=\"wp-block-heading\">Step-by-step walkthrough<\/h2>\n<p class=\"wp-block-paragraph\">Start at (0,0), visit (0,1) and (1,1). Later (2,2) starts a second island. Diagonal contact does not connect them.<\/p>\n<p class=\"wp-block-paragraph\">The example uses zero-based coordinates. The table shows each dequeued cell, the queue after exploring its neighbors, and the island count.<\/p>\n<p>CellQueue after expansionCount(0,0)[(0,1)]1(0,1)[(1,1)]1(1,1)[]1(2,2)[]2<\/p>\n<h2 class=\"wp-block-heading\">Correctness argument<\/h2>\n<p class=\"wp-block-paragraph\">Each BFS visits exactly the reachable land component. Marking on enqueue prevents duplicate work. The outer scan starts one BFS per component, so the count is exact.<\/p>\n<p class=\"wp-block-paragraph\">Soundness: only valid adjacent land is enqueued, so traversal cannot leave its component. Completeness: every reachable cell has a path from the starting cell, and processing each predecessor discovers the next cell on that path. The outer scan therefore counts each component exactly once.<\/p>\n<h2 class=\"wp-block-heading\">Complexity analysis<\/h2>\n<p class=\"wp-block-paragraph\">Both DFS and BFS take O(rows \u00d7 cols) time and O(rows \u00d7 cols) worst-case space. Recursive DFS may exceed Python recursion limits; iterative BFS avoids that issue.<\/p>\n<h2 class=\"wp-block-heading\">Edge cases<\/h2>\n<p class=\"wp-block-paragraph\">Expected results: [] \u2192 0; [[\u20180\u2019]] \u2192 0; [[\u20181\u2019]] \u2192 1; rows 11,11 \u2192 1; rows 10,01 \u2192 2. A long narrow connected grid is a useful stress test for recursion depth. Both implementations assume a rectangular grid.<\/p>\n<h2 class=\"wp-block-heading\">Interview follow-ups<\/h2>\n<p class=\"wp-block-paragraph\">Why mark when enqueuing? To avoid repeated queue entries. Is DFS slower asymptotically? No. Can we mutate the input? Only if the contract permits it.<\/p>\n<p class=\"wp-block-paragraph\"><strong>Can we use union-find?<\/strong> Yes. Union adjacent land cells and count distinct roots; useful when land is added dynamically.<\/p>\n<p class=\"wp-block-paragraph\"><strong>Why is O(rows \u00d7 cols) optimal?<\/strong> In the worst case, every cell must be inspected because any unseen cell could be an isolated island.<\/p>\n<p class=\"wp-block-paragraph\"><strong>What if diagonals connect?<\/strong> Add the four diagonal offsets to the neighbor list; the example would then contain one island.<\/p>\n<h2 class=\"wp-block-heading\">Practice and revision<\/h2>\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/leetcode.com\/problems\/number-of-islands\/\" target=\"_blank\" rel=\"noopener\">Original problem<\/a> \u00b7 <a href=\"https:\/\/programesecure.com\/dsa-roadmap\/\">DSA Roadmap<\/a><\/p>","protected":false},"excerpt":{"rendered":"<p>Given a rectangular grid of strings \u20181\u2019 (land) and \u20180\u2019 (water), return the number of connected land components. Only horizontal and vertical neighbors connect. This medium-level graph problem treats each land cell as a vertex and each valid neighbor as an edge. Example Rows 110,010,001 contain two islands. Pattern recognition and hints Hint 1: Scan [&hellip;]<\/p>\n","protected":false},"author":0,"featured_media":10599,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-10598","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-news"],"_links":{"self":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts\/10598"}],"collection":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"replies":[{"embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10598"}],"version-history":[{"count":0,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts\/10598\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/media\/10599"}],"wp:attachment":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10598"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10598"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10598"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}