<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Naincy  Jain on Medium]]></title>
        <description><![CDATA[Stories by Naincy  Jain on Medium]]></description>
        <link>https://medium.com/@naincy.codes01?source=rss-5630161afaaf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PA7SKBYIm2wLZpzP</url>
            <title>Stories by Naincy  Jain on Medium</title>
            <link>https://medium.com/@naincy.codes01?source=rss-5630161afaaf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 21:14:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@naincy.codes01/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[3 Graph Problems That Improved My Understanding of BFS, DFS and Matrix Traversal]]></title>
            <link>https://medium.com/@naincy.codes01/3-graph-problems-that-improved-my-understanding-of-bfs-dfs-and-matrix-traversal-929ebc95a979?source=rss-5630161afaaf------2</link>
            <guid isPermaLink="false">https://medium.com/p/929ebc95a979</guid>
            <category><![CDATA[dfs]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[fb]]></category>
            <category><![CDATA[graph]]></category>
            <dc:creator><![CDATA[Naincy  Jain]]></dc:creator>
            <pubDate>Wed, 11 Nov 2026 19:50:04 GMT</pubDate>
            <atom:updated>2026-11-11T19:59:31.223Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I cover three problems and the key concepts I learned while solving them:</p><ol><li>01 Matrix — Multi-Source BFS</li><li>Surrounded Regions — Boundary-Based DFS</li><li>Number of Distinct Islands — Relative Coordinates</li></ol><h3>01 Matrix: Understanding Multi-Source BFS in a 2D Grid</h3><h4>1. Understanding the Problem</h4><p>We are given a binary matrix containing 0s and 1s.</p><p>Our task is to return a matrix of the same dimensions where each cell contains the shortest distance to the nearest cell containing 0.</p><p>We can move in four directions:</p><ol><li>Up</li><li>Down</li><li>Left</li><li>Right</li></ol><p>Diagonal movements are not allowed.</p><p>The distance between two cells is the minimum number of moves required to reach one cell from the other.</p><p>Let’s understand through an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RgHNc7Ta-SPQT2mcsbpw7A.png" /></figure><pre>Input: mat = [[0,0,0],[0,1,0],[1,1,1]]<br>Output: [[0,0,0],[0,1,0],[1,2,1]]</pre><p>Let’s understand how the output is calculated.</p><p>First, let’s look at the cells that already contain 0.</p><p><strong>Cells containing 0</strong></p><p>Every cell containing 0 gets a distance of 0 because it is already the nearest zero to itself. We don&#39;t need to move anywhere to reach it.</p><p>Therefore, all zero-valued cells remain 0 in the output matrix.</p><p>Now let’s calculate the distances for the cells containing 1.</p><p><strong>Cell at (1,1)</strong></p><p>This cell contains 1.</p><p>Its neighbouring cells include (0,1), (1,0) and (1,2), all containing 0.</p><p>We need just one move to reach the nearest zero.</p><p>Therefore, its distance is 1.</p><p><strong>Cell at (2,0)</strong></p><p>This cell can reach the zero at (1,0) in one move.</p><p>Therefore, its distance is 1.</p><p><strong>Cell at (2,2)</strong></p><p>Similarly, this cell can reach the zero at (1,2) in one move.</p><p>Its distance is also 1.</p><p><strong>Cell at (2,1)</strong></p><p>This is the interesting one.</p><p>Its immediate neighbours contain 1, so we need to move further to reach the nearest zero.</p><p>For example:</p><p>(2,1) → (1,1) → (1,0)</p><p>That’s a total of two moves.</p><p>Therefore, its distance is 2.</p><h4>2. Visualizing the Matrix as a Graph</h4><p>Before jumping into an algorithm, I took the given example and started drawing it on paper.</p><p>I wanted to understand how the cells were connected and how we could move between them.</p><p>So, I started visualizing the matrix as a graph.</p><p>My thought process was:</p><ul><li>Every cell in the matrix represents a node, identified by its (row, column) coordinates.</li><li>If I can move from one cell to another in a single step, I connect those two nodes using an edge.</li><li>Since we can move only up, down, left and right, edges exist only between these four-directional neighbours.</li></ul><p>For example, consider the cell (1,1).</p><p>I connected it to:</p><ul><li>(0,1) — Up</li><li>(2,1) — Down</li><li>(1,0) — Left</li><li>(1,2) — Right</li></ul><p>I repeated the same process for every cell, connecting all the nodes wherever a valid movement was possible.</p><p>This gave me an <strong>unweighted graph</strong>, where every edge represents one move and has a cost of 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eMuk4D6DemPXbKlax1dfNA.png" /></figure><p>This visualization helped me understand that the problem was essentially asking for the shortest path from every node containing 1 to the nearest node containing 0.</p><h4>3. The Interesting Observation — Why Not Start From All Zeroes?</h4><p>After understanding the graph representation, I started thinking about how to calculate the shortest distance.</p><p>My initial thought was to start BFS from every node containing 1 and search for the nearest node containing 0.</p><p>But then I noticed something:</p><p>Every node containing 0 already has a distance of 0 from itself. We don&#39;t need to calculate anything for these nodes.</p><p>So I thought, instead of starting BFS from every 1, why don&#39;t we start from every 0?</p><p>The idea was:</p><ul><li>Every 0 node is a source with an initial distance of 0.</li><li>From each zero node, we explore its neighbouring nodes.</li><li>Whenever we encounter an unvisited 1, we calculate its distance as the current node&#39;s distance + 1.</li><li>We continue exploring until all reachable cells have been visited.</li></ul><p>Initially, I considered running BFS separately from every zero node and then taking the minimum distance for each 1.</p><p>But that would mean traversing the graph multiple times.</p><p><strong>Then I realized that we could avoid repeated BFS traversals by putting all zero nodes into the queue at the same time.</strong></p><p>This is the idea behind Multi-Source BFS.</p><p>Instead of starting from one source, we start from multiple sources and allow BFS to expand from all of them simultaneously.</p><p>This way, the first time we reach a 1 node, we have already found its shortest distance to the nearest zero.</p><h4>4. Understanding How Multi-Source BFS</h4><p>Let’s understand how I implemented the approach.</p><p><strong>1. Initialize the queue</strong></p><p>I traverse the entire matrix and insert all cells containing 0 into the queue. I mark them as visited because they are our starting points. Their distances are already 0.</p><p><strong>2. Explore all four directions</strong></p><p>I remove a node from the queue and explore its four neighbours: up, down, left and right.</p><p><strong>3. Discover unvisited cells</strong></p><p>If a neighbour:</p><ul><li>Is within matrix boundaries</li><li>Contains 1</li><li>Has not been visited</li></ul><p>I mark it as visited, calculate its distance and add it to the queue.</p><p><strong>4. Continue BFS</strong></p><p>The queue follows FIFO order, so nodes are processed level by level.</p><p>Since all zero cells were inserted initially, BFS expands from all of them simultaneously. The first time we visit a 1 cell, we have found its shortest distance to the nearest 0.</p><p>We continue until the queue becomes empty and return the distance matrix.</p><p>Let’s Dry Run With Our Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1dFgi7cu6tW6YSl4nS6og.png" /></figure><p>Consider the input:</p><pre>0  0  0<br>0  1  0<br>1  1  1</pre><p><strong>Initially:</strong></p><p>All zero cells are inserted into the queue with distance 0.</p><pre>Queue: [(0,0), (0,1), (0,2), (1,0), (1,2)]</pre><p><strong>Level 0:</strong></p><p>We process all the zero-valued nodes.</p><p>While exploring their neighbours, we discover three unvisited cells containing 1:</p><ul><li>(1,1) → distance 1</li><li>(2,0) → distance 1</li><li>(2,2) → distance 1</li></ul><p>These cells are marked visited and added to the queue.</p><pre>Queue: [(1,1), (2,0), (2,2)]</pre><p><strong>Level 1:</strong></p><p>Now we process these three newly discovered nodes.</p><p>While exploring their neighbours, we discover (2,1) for the first time.</p><p>Its distance becomes:</p><pre>dist[2][1] = dist[2][0] + 1<br>           = 1 + 1<br>           = 2</pre><p>We mark it visited and add it to the queue.</p><pre>Queue: [(2,1)]</pre><p><strong>Level 2:</strong></p><p>We process (2,1). All its valid neighbours have already been visited, so no new nodes are added.</p><p>The queue eventually becomes empty.</p><p><strong>Final Distance Matrix:</strong></p><pre>0  0  0<br>0  1  0<br>1  2  1</pre><h4>5. Java Implementation</h4><pre>class Solution {<br><br>    record Pair&lt;A, B&gt;(A first, B second) {}<br><br>    public int[][] updateMatrix(int[][] mat) {<br><br>        int rows = mat.length;<br>        int cols = mat[0].length;<br><br>        int[][] distance = new int[rows][cols];<br><br>        Queue&lt;Pair&lt;Integer, Integer&gt;&gt; queue =<br>            new LinkedList&lt;&gt;();<br><br>        boolean[][] visited = new boolean[rows][cols];<br><br>        for (int row = 0; row &lt; rows; row++) {<br>            for (int col = 0; col &lt; cols; col++) {<br><br>                if (mat[row][col] == 0) {<br>                    queue.offer(new Pair&lt;&gt;(row, col));<br>                    visited[row][col] = true;<br>                }<br>            }<br>        }<br><br>        int[][] directions = {<br>            {-1, 0},<br>            {0, -1},<br>            {1, 0},<br>            {0, 1}<br>        };<br><br>        while (!queue.isEmpty()) {<br><br>            Pair&lt;Integer, Integer&gt; currentCell = queue.poll();<br><br>            int currentRow = currentCell.first();<br>            int currentCol = currentCell.second();<br><br>            for (int direction = 0; direction &lt; 4; direction++) {<br><br>                int nextRow = currentRow + directions[direction][0];<br>                int nextCol = currentCol + directions[direction][1];<br><br>                if (nextRow &gt;= 0 &amp;&amp; nextRow &lt; rows &amp;&amp;<br>                    nextCol &gt;= 0 &amp;&amp; nextCol &lt; cols &amp;&amp;<br>                    mat[nextRow][nextCol] == 1 &amp;&amp;<br>                    !visited[nextRow][nextCol]) {<br><br>                    visited[nextRow][nextCol] = true;<br><br>                    distance[nextRow][nextCol] =<br>                        distance[currentRow][currentCol] + 1;<br><br>                    queue.offer(new Pair&lt;&gt;(nextRow, nextCol));<br>                }<br>            }<br>        }<br><br>        return distance;<br>    }<br>}</pre><p>Understanding the Implementation</p><ul><li><strong>Queue initialization:</strong> Add all cells containing 0 to the queue and mark them as visited. These are our multiple starting points.</li><li><strong>Direction array:</strong> Defines the four possible movements: up, down, left and right.</li><li><strong>BFS traversal:</strong> Process each cell from the queue and explore its four neighbours.</li><li><strong>Distance calculation:</strong> When an unvisited 1 is discovered, its distance is calculated as the current cell&#39;s distance + 1.</li><li><strong>Visited array:</strong> Ensures that each cell is processed only once, preventing duplicate visits.</li></ul><p>Since all zero cells are inserted initially, BFS expands from multiple sources simultaneously. The first time a cell containing 1 is visited, its shortest distance to the nearest zero is determined.</p><h4>6. Complexity Analysis</h4><p>Let m be the number of rows and n be the number of columns.</p><p><strong>Time Complexity: O(m × n)</strong></p><p>We traverse the matrix to initialize the queue. During BFS, each cell is visited at most once, and we check four directions for every cell.</p><p><strong>Space Complexity: O(m × n)</strong></p><p>We use a distance matrix, a visited matrix, and a queue, each requiring at most O(m × n) space.</p><p>Therefore, the overall <strong>time and space complexity is O(m × n)</strong>.</p><h3>Surrounded Regions: Stop Finding What to Capture, Find What to Protect</h3><h4>1. Understanding the Problem</h4><p>We are given a 2D matrix containing two characters: X and O.</p><p>Our task is to capture all regions of O that are completely surrounded by X.</p><p>A region consists of horizontally or vertically connected O cells.</p><p>A region is considered surrounded if none of its O cells are present on the boundary of the matrix.</p><p>If a region is surrounded, we must replace all its O cells with X. However, if even one cell in a connected region touches the boundary, the entire region must remain unchanged.</p><p>Let’s understand this through an example.</p><p><strong>Input:</strong></p><pre>X X X X<br>X O O X<br>X X O X<br>X O X X</pre><p><strong>Output:</strong></p><pre>X X X X<br>X X X X<br>X X X X<br>X O X X</pre><p>Let’s understand what happened.</p><p><strong>The surrounded region</strong></p><p>Consider the connected O cells at:</p><ul><li>(1,1)</li><li>(1,2)</li><li>(2,2)</li></ul><p>These cells are connected to each other, but none of them touches the boundary.</p><p>They are completely enclosed by X, so we capture this region by replacing all three O cells with X.</p><p><strong>The boundary-connected region</strong></p><p>Now consider the O at (3,1).</p><p>It is located on the bottom boundary of the matrix.</p><p>Since it touches the boundary, it cannot be completely surrounded by X.</p><p>Therefore, it remains unchanged.</p><p>This helped me understand one important condition:</p><p><strong>If a connected region contains even one boundary </strong><strong>O, the entire region must be protected.</strong></p><h4>2. Visualizing the Matrix as a Graph</h4><p>Just like the previous problem, I started by visualizing the matrix as a graph.</p><p>My thought process was:</p><ul><li>Every cell represents a node, identified by its (row, column) coordinates.</li><li>Two nodes are connected if their cells are adjacent horizontally or vertically.</li><li>We can use DFS to explore all connected O cells and identify their connected components.</li></ul><p>For example, consider the region containing (1,1).</p><p>From this cell, we can reach:</p><ul><li>(1,2)</li><li>(2,2)</li></ul><p>All these cells form one connected component.</p><p>Similarly, (3,1) forms another connected component.</p><p>Now the problem becomes:</p><p><strong>How do we identify which connected components should be captured and which should be protected?</strong></p><p>Initially, I thought I could explore each connected component using DFS, check whether it touches the boundary, and then decide whether to capture it.</p><p>That was my first approach.</p><h4>3. My Initial Approach — Using DFS and a Boundary Flag</h4><p>My initial idea was to explore every connected component of O cells using DFS.</p><p>I wanted to maintain a boolean variable called flag to check whether the current connected component touched the boundary.</p><p>My approach was:</p><ol><li>Traverse the matrix and find an unvisited O cell.</li><li>Start DFS from that cell.</li><li>Explore all its connected O neighbours.</li><li>If any cell in the component touches the boundary, set flag to true.</li><li>If the flag remains false, convert the visited cells to X.</li></ol><p>The idea was that if the entire connected component did not touch the boundary, it must be surrounded.</p><p>This was my first implementation.</p><h4>4. My First Java Implementation</h4><pre>class Solution {<br><br>    boolean flag = false;<br><br>    int[][] dir = {<br>        {-1, 0},<br>        {0, -1},<br>        {1, 0},<br>        {0, 1}<br>    };<br><br>    public void dfs(int i, int j, int m, int n,<br>                    char[][] grid, boolean[][] vis) {<br><br>        vis[i][j] = true;<br><br>        if (i == m - 1 || j == n - 1 || i == 0 || j == 0) {<br>            flag = true;<br>        }<br><br>        for (int k = 0; k &lt; 4; k++) {<br><br>            int ni = i + dir[k][0];<br>            int ny = j + dir[k][1];<br><br>            if (ni &gt;= 0 &amp;&amp; ni &lt; m &amp;&amp;<br>                ny &gt;= 0 &amp;&amp; ny &lt; n &amp;&amp;<br>                !vis[ni][ny] &amp;&amp; grid[ni][ny] == &#39;O&#39;) {<br><br>                dfs(ni, ny, m, n, grid, vis);<br>            }<br>        }<br><br>        if (flag == false) {<br>            grid[i][j] = &#39;X&#39;;<br>        }<br>    }<br><br>    public void solve(char[][] grid) {<br><br>        int m = grid.length;<br>        int n = grid[0].length;<br><br>        boolean[][] vis = new boolean[m][n];<br><br>        for (int i = 0; i &lt; m; i++) {<br>            for (int j = 0; j &lt; n; j++) {<br><br>                if (!vis[i][j] &amp;&amp; grid[i][j] == &#39;O&#39;) {<br><br>                    flag = false;<br><br>                    dfs(i, j, m, n, grid, vis);<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>However, this implementation passed only <strong>55 out of 59 test cases</strong>.</p><h4>5. Why Did My First Implementation Fail?</h4><p>The issue was with how I was using the shared flag variable and modifying the matrix during recursion.</p><p>DFS explores one branch at a time.</p><p>Imagine a connected component where DFS first explores an interior branch that does not touch the boundary.</p><p>At that point, flag is still false, because no boundary cell has been discovered yet.</p><p>When the recursive calls return, my code executes:</p><pre>if (flag == false) {<br>    grid[i][j] = &#39;X&#39;;<br>}</pre><p>So, some cells are converted to X before DFS has finished exploring the entire connected component.</p><p>But another branch of the same component might eventually reach a boundary cell.</p><p>When that happens, flag becomes true.</p><p>Unfortunately, the cells that were already converted to X cannot be restored to their original state. The original connection has already been lost.</p><p>This is what caused the incorrect output.</p><p><strong>My mistake was making the decision to capture cells before completing the traversal of the entire connected component.</strong></p><p>I needed to explore the entire component first and only then decide whether to capture it.</p><h4>6. The Important Observation — What If We Start From the Boundary?</h4><p>After getting a hint, I started looking at the problem from the opposite direction.</p><p>Instead of searching for regions that should be captured, I asked myself:</p><p><strong>What if I first find all the regions that should NOT be captured?</strong></p><p>Think about it:</p><ul><li>Any O present on the boundary cannot be captured.</li><li>Any O connected to a boundary O also cannot be captured.</li><li>Therefore, every O that is not connected to any boundary O must be surrounded.</li></ul><p>This gave me a much simpler approach.</p><p>Instead of starting DFS from every O cell, I can:</p><ol><li>Traverse the boundary of the matrix.</li><li>Whenever I find an O, start DFS from that cell.</li><li>Mark every connected O as safe.</li><li>After processing all boundary cells, convert the remaining O cells to X.</li><li>Restore the safe cells to O.</li></ol><p>This is the key idea:</p><p><strong>Start from the boundary and protect everything connected to it. Whatever remains must be captured.</strong></p><h4>7. Understanding the Boundary-First DFS Approach</h4><p>Let’s break down how I implemented this approach.</p><p><strong>1. Traverse the boundaries</strong></p><p>I iterate over the first and last rows, followed by the first and last columns.</p><p>Whenever I encounter an O that has not been visited, I start DFS from that cell.</p><p>These are our starting points because every boundary-connected region must be preserved.</p><p><strong>2. Explore connected </strong><strong>O cells using DFS</strong></p><p>For every boundary O, DFS explores its four neighbours:</p><ul><li>Up</li><li>Down</li><li>Left</li><li>Right</li></ul><p>Whenever it finds an unvisited neighbouring O, it recursively explores that cell.</p><p><strong>3. Mark safe cells</strong></p><p>Instead of converting these cells to X, I temporarily replace them with #.</p><p>This # represents a safe cell that is connected to the boundary and must not be captured.</p><p>I also mark the cell as visited to avoid processing it again.</p><p><strong>4. Capture the remaining regions</strong></p><p>After all boundary-connected regions have been explored, I traverse the entire matrix again.</p><p>Now there are three possibilities:</p><ul><li># means the cell is safe, so restore it to O.</li><li>O means the cell was never reached from the boundary, so convert it to X.</li><li>X remains unchanged.</li></ul><p>This way, we don’t need to check whether each connected component is surrounded individually.</p><p>We simply protect the boundary-connected cells and capture everything else.</p><h4>8. Dry Run With Our Example</h4><p>Consider the input:</p><pre>X X X X<br>X O O X<br>X X O X<br>X O X X</pre><p><strong>Initially:</strong></p><p>We start traversing the boundaries.</p><p>The only boundary cell containing O is (3,1).</p><p>We start DFS from this cell.</p><p><strong>Boundary DFS:</strong></p><p>We mark (3,1) as #.</p><p>Its valid neighbours do not contain any additional O cells.</p><p>Therefore, DFS finishes.</p><p>The matrix now looks like this:</p><pre>X X X X<br>X O O X<br>X X O X<br>X # X X</pre><p><strong>Final traversal:</strong></p><p>Now we traverse the entire matrix.</p><ul><li>The three remaining O cells are not connected to any boundary O, so we convert them to X.</li><li>The # cell is safe, so we restore it to O.</li><li>All existing X cells remain unchanged.</li></ul><p><strong>Final Matrix:</strong></p><pre>X X X X<br>X X X X<br>X X X X<br>X O X X</pre><p>We successfully captured the surrounded region while preserving the boundary-connected region.</p><h4>9. Final Java Implementation</h4><pre>class Solution {<br><br>    int[][] dir = {<br>        {-1, 0},<br>        {0, -1},<br>        {1, 0},<br>        {0, 1}<br>    };<br><br>    public void dfs(int i, int j, int m, int n,<br>                    char[][] grid, boolean[][] vis) {<br><br>        vis[i][j] = true;<br>        grid[i][j] = &#39;#&#39;;<br><br>        for (int k = 0; k &lt; 4; k++) {<br><br>            int ni = i + dir[k][0];<br>            int ny = j + dir[k][1];<br><br>            if (ni &gt;= 0 &amp;&amp; ni &lt; m &amp;&amp;<br>                ny &gt;= 0 &amp;&amp; ny &lt; n &amp;&amp;<br>                !vis[ni][ny] &amp;&amp; grid[ni][ny] == &#39;O&#39;) {<br><br>                dfs(ni, ny, m, n, grid, vis);<br>            }<br>        }<br>    }<br><br>    public void solve(char[][] grid) {<br><br>        int m = grid.length;<br>        int n = grid[0].length;<br><br>        boolean[][] vis = new boolean[m][n];<br><br>        for (int i = 0; i &lt; n; i++) {<br><br>            if (!vis[0][i] &amp;&amp; grid[0][i] == &#39;O&#39;) {<br>                dfs(0, i, m, n, grid, vis);<br>            }<br><br>            if (!vis[m - 1][i] &amp;&amp; grid[m - 1][i] == &#39;O&#39;) {<br>                dfs(m - 1, i, m, n, grid, vis);<br>            }<br>        }<br><br>        for (int i = 0; i &lt; m; i++) {<br><br>            if (!vis[i][0] &amp;&amp; grid[i][0] == &#39;O&#39;) {<br>                dfs(i, 0, m, n, grid, vis);<br>            }<br><br>            if (!vis[i][n - 1] &amp;&amp; grid[i][n - 1] == &#39;O&#39;) {<br>                dfs(i, n - 1, m, n, grid, vis);<br>            }<br>        }<br><br>        for (int i = 0; i &lt; m; i++) {<br>            for (int j = 0; j &lt; n; j++) {<br><br>                if (grid[i][j] == &#39;#&#39;) {<br>                    grid[i][j] = &#39;O&#39;;<br>                } else if (grid[i][j] == &#39;O&#39;) {<br>                    grid[i][j] = &#39;X&#39;;<br>                }<br>            }<br>        }<br>    }<br>}</pre><h4>10. Understanding the Implementation</h4><ul><li><strong>Direction array:</strong> Defines the four possible movements: up, down, left and right.</li><li><strong>Boundary traversal:</strong> Checks the first and last rows and columns for O cells.</li><li><strong>DFS traversal:</strong> Explores all connected O cells starting from a boundary cell.</li><li><strong>Safe-cell marking:</strong> Temporarily changes boundary-connected O cells to # so they can be identified later.</li><li><strong>Final matrix traversal:</strong> Restores # to O and converts all remaining O cells to X.</li></ul><p>The visited matrix ensures that each cell is explored only once. The temporary # marker helps us distinguish safe cells from surrounded cells during the final traversal.</p><p>Since all boundary-connected O cells are marked before we modify the remaining cells, we no longer have to worry about making a decision too early during DFS.</p><h4>11. Complexity Analysis</h4><p>Let m be the number of rows and n be the number of columns.</p><p><strong>Time Complexity: O(m × n)</strong></p><p>We traverse the boundaries and perform DFS on boundary-connected regions. Each cell is visited at most once during DFS.</p><p>We then traverse the entire matrix once more to restore safe cells and capture the remaining ones.</p><p>Therefore, the overall time complexity is <strong>O(m × n)</strong>.</p><p><strong>Space Complexity: O(m × n)</strong></p><p>We use a visited matrix of size m × n.</p><p>Additionally, the recursive DFS call stack can grow up to O(m × n) in the worst case.</p><p>Therefore, the overall auxiliary space complexity is <strong>O(m × n)</strong>.</p><h4>What I Learned</h4><p>My biggest learning from this problem was that sometimes it is easier to identify what must be preserved rather than directly searching for what must be changed.</p><p>My first approach tried to capture surrounded regions while DFS was still exploring them. The boundary-first approach made the decision much simpler: protect everything connected to the boundary, and capture whatever remains.</p><p>It also reminded me that in recursive algorithms, modifying shared data before the full traversal is complete can lead to unexpected results.</p><h3>Same Shape, Different Position: Understanding Number of Distinct Islands Using Relative Coordinates</h3><h4>1. Understanding the Problem</h4><p>We are given a 2D grid containing:</p><ul><li>L representing land.</li><li>W representing water.</li></ul><p>Our task is to count the number of distinct island shapes.</p><p>An island consists of connected land cells. Two cells are connected if they are adjacent horizontally or vertically.</p><p>Two islands are considered identical if they have the same shape, even if they are located at different positions in the grid.</p><p>Let’s understand this through an example.</p><p><strong>Input:</strong></p><pre>L L W W W W<br>L W W L L L<br>W W W L W W<br>W L W W W W<br>W L L W L L</pre><p><strong>Output: </strong><strong>4</strong></p><p>There are four islands in this grid, and all four have different shapes.</p><p>The important thing to understand is that we are not counting the total number of islands. We are counting the number of unique island shapes.</p><h4>2. The Important Observation — How Do We Compare Island Shapes?</h4><p>Initially, I thought about storing the actual coordinates of every cell belonging to an island.</p><p>But how could I determine whether two islands had the same shape when they were located at different positions?</p><p>I started thinking about comparing the corresponding coordinates of two islands by subtracting them.</p><p>Let’s consider two islands:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZAJbMmQCNb-vS0LBgS57w.png" /></figure><p>Notice something interesting!</p><p>All three differences are exactly the same: (2,3).</p><p>This means every cell in Island 2 has shifted by the same amount compared to Island 1.</p><p>This gave me an important observation:</p><p><strong>If the difference between corresponding coordinates of two islands is the same, their shapes are identical under translation.</strong></p><h4>3. The Key Observation — Relative Coordinates</h4><p>Now, instead of comparing every island with every other island, I wanted a way to represent each island independently so that I could compare them directly.</p><p>That’s when I thought of using the first cell of each island as a reference point.</p><p>Suppose the starting cell of an island is (initialRow, initialCol).</p><p>For every cell (row, col) belonging to that island, I calculate:</p><p>(row-initialRow, col-initialCol)</p><p>Let’s apply this to our two islands.</p><p><strong>Island 1:</strong> Starting point (0,0)</p><p>{(0,0), (0,1), (1,0)}</p><p><strong>Island 2:</strong> Starting point (2,3)</p><p>{(0,0), (0,1), (1,0)}</p><p>Now both islands have exactly the same representation!</p><p>By subtracting the starting coordinates from every cell, I effectively shift each island so that its starting cell becomes (0,0).</p><p>Every other cell retains its relative position with respect to that starting point.</p><p>This is called <strong>normalizing coordinates using a reference point</strong>.</p><p>Now I don’t need to compare islands pair by pair. I can simply store their normalized coordinate representations in a HashSet.</p><p>If a shape already exists in the set, it is a duplicate. Otherwise, it is a new distinct island.</p><p>One important distinction: this approach identifies identical shapes under translation only. Rotated or reflected islands are not automatically considered identical.</p><h4>4. Understanding the Algorithm</h4><p>Once I understood relative coordinates, the algorithm became straightforward.</p><ol><li>Traverse the entire grid and find an unvisited land cell.</li><li>Start DFS from that cell to explore the complete island.</li><li>Use the starting cell’s coordinates as the reference point.</li><li>For every visited land cell, calculate its relative coordinates and store them in a set.</li><li>Once DFS finishes, add the island’s coordinate set to another set containing all distinct shapes.</li><li>Return the size of the outer set.</li></ol><p>Since we use a HashSet, duplicate island shapes are automatically ignored.</p><h4>5. Java Implementation</h4><pre><br><br>import java.util.*;<br><br>class Solution {<br><br>    record Pair&lt;A, B&gt;(A first, B second) {}<br><br>    int[][] directions = {<br>        {-1, 0},<br>        {0, -1},<br>        {1, 0},<br>        {0, 1}<br>    };<br><br>    public void dfs(int row, int col, char[][] grid, boolean[][] visited,<br>                    int rows, int cols, Set&lt;Pair&lt;Integer, Integer&gt;&gt; islandShape,<br>                    int startRow, int startCol) {<br><br>        visited[row][col] = true;<br><br>        islandShape.add(new Pair&lt;&gt;(row - startRow, col - startCol));<br><br>        for (int[] direction : directions) {<br>            int nextRow = row + direction[0];<br>            int nextCol = col + direction[1];<br><br>            if (nextRow &gt;= 0 &amp;&amp; nextRow &lt; rows &amp;&amp;<br>                nextCol &gt;= 0 &amp;&amp; nextCol &lt; cols &amp;&amp;<br>                !visited[nextRow][nextCol] &amp;&amp;<br>                grid[nextRow][nextCol] == &#39;L&#39;) {<br><br>                dfs(nextRow, nextCol, grid, visited, rows, cols,<br>                    islandShape, startRow, startCol);<br>            }<br>        }<br>    }<br><br>    public int countDistinctIslands(char[][] grid) {<br>        int rows = grid.length;<br>        int cols = grid[0].length;<br><br>        boolean[][] visited = new boolean[rows][cols];<br><br>        Set&lt;Set&lt;Pair&lt;Integer, Integer&gt;&gt;&gt; distinctIslandShapes = new HashSet&lt;&gt;();<br><br>        for (int row = 0; row &lt; rows; row++) {<br>            for (int col = 0; col &lt; cols; col++) {<br><br>                if (!visited[row][col] &amp;&amp; grid[row][col] == &#39;L&#39;) {<br>                    Set&lt;Pair&lt;Integer, Integer&gt;&gt; islandShape = new HashSet&lt;&gt;();<br><br>                    dfs(row, col, grid, visited, rows, cols,<br>                        islandShape, row, col);<br><br>                    distinctIslandShapes.add(islandShape);<br>                }<br>            }<br>        }<br><br>        return distinctIslandShapes.size();<br>    }<br>}</pre><h4>6. Understanding the Implementation</h4><ul><li><strong>Matrix traversal:</strong> Finds every unvisited land cell (L) and starts DFS to explore a new island.</li><li><strong>DFS traversal:</strong> Visits all connected land cells and marks them as visited.</li><li><strong>Relative coordinates:</strong> Subtracts the starting cell’s coordinates from every visited cell to create a normalized island shape.</li><li><strong>Island representation:</strong> Stores the relative coordinates in a HashSet.</li><li><strong>Distinct shape storage:</strong> Stores each island’s coordinate set in an outer HashSet, which automatically ignores duplicate shapes.</li></ul><p>Finally, the size of the outer set gives us the number of distinct island shapes.</p><h4>7. Complexity Analysis</h4><p>Let m be the number of rows and n be the number of columns.</p><p><strong>Time Complexity: O(m × n)</strong></p><p>We traverse the entire grid, and every land cell is visited at most once during DFS. For each cell, we check four directions, which takes constant time.</p><p>HashSet operations take O(1) on average.</p><p>Therefore, the overall expected time complexity is <strong>O(m × n)</strong>.</p><p><strong>Space Complexity: O(m × n)</strong></p><h4>What I Learned</h4><p>The biggest learning from this problem was understanding how to compare shapes independently of their positions.</p><h3>Final Thoughts</h3><p>These three problems taught me that solving a problem is not just about finding the right algorithm. It’s also about understanding the problem, identifying the right observation, and improving my approach when something doesn’t work.</p><p>Here are my key takeaways:</p><ul><li><strong>01 Matrix:</strong> Understanding Multi-Source BFS and how it finds the shortest distance from multiple starting points.</li><li><strong>Surrounded Regions:</strong> Learning to approach a problem from the opposite direction — finding what to protect instead of what to capture.</li><li><strong>Number of Distinct Islands:</strong> Understanding how relative coordinates help compare shapes independently of their positions.</li></ul><p>I’m sharing my learning process, not just the final solutions. I want to document how I think, where I get stuck, and what I learn along the way.</p><h4>Problems Covered</h4><ol><li><a href="https://leetcode.com/problems/01-matrix/">01 Matrix — LeetCode</a></li><li><a href="https://leetcode.com/problems/surrounded-regions/">Surrounded Regions — LeetCode</a></li><li><a href="https://www.geeksforgeeks.org/problems/number-of-distinct-islands/1">Number of Distinct Islands — GeeksforGeeks</a></li></ol><p>If you found this article helpful, feel free to <strong>clap, share, or leave your thoughts in the comments.</strong></p><p>I’m learning in public, one problem at a time. More learnings coming soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=929ebc95a979" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>