{"id":177,"date":"2025-05-27T17:45:39","date_gmt":"2025-05-27T12:15:39","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=177"},"modified":"2025-05-27T17:49:12","modified_gmt":"2025-05-27T12:19:12","slug":"number-of-enclaves-leetcode-1020","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/number-of-enclaves-leetcode-1020\/","title":{"rendered":"Number of Enclaves | Leetcode 1020 | Explained using BFS"},"content":{"rendered":"\n<p>Learn how to count the number of land cells in a grid that cannot reach the border by water. This step-by-step guide uses a multi-source BFS approach with clear, plain-English explanations and in-place code comments.<\/p>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-22e38476-5bdd-4176-b181-3a769c62ef84\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Content:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-enclaves-leetcode-1020\/#0-what-the-problem-asks\" style=\"\">What the Problem Asks<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-enclaves-leetcode-1020\/#1-intuition-amp-approach\" style=\"\">Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-enclaves-leetcode-1020\/#2-code-implementation-with-comments\" style=\"\">Code Implementation (with Comments)<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-enclaves-leetcode-1020\/#3-detailed-explanation\" style=\"\">Detailed Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-enclaves-leetcode-1020\/#4-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-enclaves-leetcode-1020\/#5-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"0-what-the-problem-asks\">What the Problem Asks<\/h2>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>You are given an <code>m x n<\/code> binary grid <code>grid<\/code> where <code>0<\/code> represents water and <code>1<\/code> represents land.<br>A move consists of walking from one land cell to another adjacent (4-directional) land cell.<br>A land cell is called an <strong>enclave<\/strong> if it cannot reach the boundary of the grid by any number of moves.<br>Return <em>the number of land cells in all enclaves<\/em>.<\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-intuition-amp-approach\">Intuition &amp; Approach<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Why BFS from the Border?<\/strong><br>Any land (<code>1<\/code>) that can <em>reach<\/em> the boundary is <strong>not<\/strong> an enclave. If we start BFS from <em>all<\/em> boundary land cells, we can mark every land cell that\u2019s connected to the edge.<\/li>\n\n\n\n<li><strong>What\u2019s Left Over?<\/strong><br>After that BFS, any land cell <strong>not<\/strong> visited must be unable to reach the border, that\u2019s exactly the count we want.<\/li>\n\n\n\n<li><strong>High-Level Steps:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Create a <code>visited<\/code> grid, same size as <code>grid<\/code>, initialized to <code>0<\/code> (unvisited).<\/li>\n\n\n\n<li>Enqueue every land cell on the four borders and mark them visited.<\/li>\n\n\n\n<li>Run BFS: for each cell popped, enqueue its unvisited land neighbors and mark them.<\/li>\n\n\n\n<li>Finally, scan the entire grid: every land cell that is still unvisited is an enclave, increment a counter.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-code-implementation-with-comments\">Code Implementation (with Comments)<\/h2>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"from collections import deque\n\nclass Solution:\n    def numEnclaves(self, grid: List[List[int]]) -&gt; int:\n        rows = len(grid)\n        cols = len(grid[0])\n        # visited[r][c] == 1 means we've seen this land cell in BFS\n        visited = [[0 for _ in range(cols)] for _ in range(rows)]\n        queue = deque()\n\n        # 1. Enqueue all land cells on the border\n        for r in range(rows):\n            for c in range(cols):\n                # Is this cell on the outer border?\n                if r == 0 or c == 0 or r == rows - 1 or c == cols - 1:\n                    # If it's land, mark visited and enqueue\n                    if grid[r][c] == 1:\n                        queue.append((r, c))\n                        visited[r][c] = 1\n\n        # 2. BFS to mark all land cells reachable from the border\n        while len(queue) != 0:\n            i, j = queue.popleft()\n            # Explore up, left, down, right\n            for x, y in [(-1, 0), (0, -1), (1, 0), (0, 1)]:\n                new_i, new_j = i + x, j + y\n                # Skip out-of-bounds\n                if new_i &lt; 0 or new_i &gt;= rows or new_j &lt; 0 or new_j &gt;= cols:\n                    continue\n                # Skip water\n                if grid[new_i][new_j] == 0:\n                    continue\n                # Skip already visited land\n                if visited[new_i][new_j] == 1:\n                    continue\n                # Mark and enqueue this land cell\n                queue.append((new_i, new_j))\n                visited[new_i][new_j] = 1\n\n        # 3. Count all land cells that were never visited\n        count = 0\n        for r in range(rows):\n            for c in range(cols):\n                if grid[r][c] == 1 and visited[r][c] == 0:\n                    count += 1\n\n        return count\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> collections <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> deque<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">numEnclaves<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">grid<\/span><span style=\"color: #D4D4D4\">: List[List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]]) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        rows = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(grid)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        cols = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(grid[<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">])<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># visited[r][c] == 1 means we&#39;ve seen this land cell in BFS<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        visited = [[<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(cols)] <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(rows)]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        queue = deque()<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># 1. Enqueue all land cells on the border<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> r <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(rows):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> c <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(cols):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Is this cell on the outer border?<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> r == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">or<\/span><span style=\"color: #D4D4D4\"> c == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">or<\/span><span style=\"color: #D4D4D4\"> r == rows - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">or<\/span><span style=\"color: #D4D4D4\"> c == cols - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #6A9955\"># If it&#39;s land, mark visited and enqueue<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> grid[r][c] == <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                        queue.append((r, c))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                        visited[r][c] = <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># 2. BFS to mark all land cells reachable from the border<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(queue) != <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            i, j = queue.popleft()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># Explore up, left, down, right<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> x, y <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> [(-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">), (<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">), (<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">), (<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                new_i, new_j = i + x, j + y<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Skip out-of-bounds<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> new_i &lt; <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">or<\/span><span style=\"color: #D4D4D4\"> new_i &gt;= rows <\/span><span style=\"color: #569CD6\">or<\/span><span style=\"color: #D4D4D4\"> new_j &lt; <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">or<\/span><span style=\"color: #D4D4D4\"> new_j &gt;= cols:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #C586C0\">continue<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Skip water<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> grid[new_i][new_j] == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #C586C0\">continue<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Skip already visited land<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> visited[new_i][new_j] == <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #C586C0\">continue<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Mark and enqueue this land cell<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                queue.append((new_i, new_j))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                visited[new_i][new_j] = <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># 3. Count all land cells that were never visited<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        count = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> r <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(rows):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> c <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(cols):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> grid[r][c] == <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> visited[r][c] == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    count += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> count<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"3-detailed-explanation\">Detailed Explanation<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Setup<\/strong>\n<ul class=\"wp-block-list\">\n<li>We read the grid size into <code>rows<\/code> and <code>cols<\/code>.<\/li>\n\n\n\n<li>We build a <code>visited<\/code> matrix initialized to <code>0<\/code> for every cell.<\/li>\n\n\n\n<li>We make an empty queue for our BFS.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Border Enqueue<\/strong>\n<ul class=\"wp-block-list\">\n<li>We loop over every cell in the first row, last row, first column, and last column.<\/li>\n\n\n\n<li>Whenever we see a land cell (<code>grid[r][c] == 1<\/code>), we mark <code>visited[r][c] = 1<\/code> and add <code>(r, c)<\/code> to the queue.<\/li>\n\n\n\n<li>This seeds our BFS with <strong>all<\/strong> border land cells at distance 0 from the edge.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Multi-Source BFS<\/strong>\n<ul class=\"wp-block-list\">\n<li>While the queue isn\u2019t empty, we pop <code>(i, j)<\/code>.<\/li>\n\n\n\n<li>We look at its four neighbors: up, left, down, right.\n<ul class=\"wp-block-list\">\n<li>If the neighbor is out of bounds, skip it.<\/li>\n\n\n\n<li>If it\u2019s water (<code>0<\/code>), skip it.<\/li>\n\n\n\n<li>If it\u2019s already visited, skip it.<\/li>\n\n\n\n<li>Otherwise, it\u2019s unvisited land: we mark it visited and enqueue it.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>This process floods inward from the border, marking every land cell that can reach the edge.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Counting Enclaves<\/strong>\n<ul class=\"wp-block-list\">\n<li>After BFS, any land cell with <code>visited[r][c] == 0<\/code> was never reached by our border-based flood.<\/li>\n\n\n\n<li>We loop over all cells once more and count those unvisited land cells.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"4-time-and-space-complexity\">Time and Space Complexity<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong> O(m\u00b7n) \u2014 we visit each cell at most twice (once to enqueue, once to process).<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong> O(m\u00b7n) \u2014 for the <code>visited<\/code> matrix and the BFS queue in the worst case.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5-conclusion\">Conclusion<\/h2>\n\n\n\n<p>By starting BFS from all border land cells at once, we efficiently mark every land cell that can \u201cescape\u201d to the boundary. The rest are true enclaves and get counted. This multi-source BFS runs in linear time and uses only O(m\u00b7n) extra space, perfect for grids up to a few hundred in each dimension. Happy coding!<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/www.codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\">+91-9712928220<\/a>.<\/em><\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to count the number of land cells in a grid that cannot reach the border by water. This step-by-step guide uses a multi-source BFS approach with clear, plain-English explanations and in-place code comments. What the Problem Asks You are given an m x n binary grid grid where 0 represents water and 1<\/p>\n","protected":false},"author":1,"featured_media":180,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,5],"tags":[17,18],"class_list":{"0":"post-177","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-expert","9":"tag-graph","10":"tag-hard"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/05\/number-of-enclaves-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/177","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=177"}],"version-history":[{"count":3,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/177\/revisions"}],"predecessor-version":[{"id":226,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/177\/revisions\/226"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/180"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=177"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=177"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=177"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}