{"id":160,"date":"2025-05-26T19:40:21","date_gmt":"2025-05-26T14:10:21","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=160"},"modified":"2025-05-27T11:34:12","modified_gmt":"2025-05-27T06:04:12","slug":"01-matrix-leetcode-542","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/01-matrix-leetcode-542\/","title":{"rendered":"01 Matrix | Leetcode 542 | Explained using BFS"},"content":{"rendered":"\n<p>Learn how to solve the <strong>\u201c01 Matrix\u201d<\/strong> problem (LeetCode <strong>542<\/strong>) by using a multi-source breadth-first search. We walk through the Python code, explain each step, run a dry example, and analyze complexity.<\/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-86967e49-d879-4dbd-aa02-54e1d05dcc8d\" 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\/01-matrix-leetcode-542\/#0-what-the-problem-asks\" style=\"\">What the Problem Asks<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/01-matrix-leetcode-542\/#1-intuition-amp-approach\" style=\"\">Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/01-matrix-leetcode-542\/#2-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/01-matrix-leetcode-542\/#3-step-by-step-explanation\" style=\"\">Step-by-Step Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/01-matrix-leetcode-542\/#4-dry-run-example\" style=\"\">Dry Run Example<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/01-matrix-leetcode-542\/#5-time-amp-space-complexity\" style=\"\">Time &amp; Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/01-matrix-leetcode-542\/#6-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><strong>LeetCode 542: 01 Matrix<\/strong><br>Given an <code>m x n<\/code> binary matrix <code>mat<\/code> of <code>0<\/code>s and <code>1<\/code>s, return a matrix <code>dist<\/code> where <code>dist[i][j]<\/code> is the distance of the nearest <code>0<\/code> to cell <code>(i, j)<\/code>. Distance is measured in number of steps moving vertically or horizontally.<\/p>\n<\/blockquote>\n\n\n\n<p><strong>Input:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>mat<\/code>: 2D list of integers <code>0<\/code> or <code>1<\/code>.<\/li>\n<\/ul>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>2D list <code>distance<\/code> of same shape, where each cell holds the minimum distance to any <code>0<\/code> in <code>mat<\/code><\/li>\n<\/ul>\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>Multi-Source BFS:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Instead of running BFS from <em>every<\/em> <code>1<\/code> cell (which would be slow), we enqueue <em>all<\/em> <code>0<\/code> cells initially.<\/li>\n\n\n\n<li>Then we expand outward in waves. The first time we reach a <code>1<\/code>, its distance is the BFS level at which we discover it.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Why It Works:<\/strong>\n<ul class=\"wp-block-list\">\n<li>BFS guarantees that when a cell is first visited, it\u2019s via the shortest path from any source\u2014in this case, the nearest <code>0<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>High-Level Steps:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Initialize <code>distance<\/code> and <code>visited<\/code> arrays (both zeros).<\/li>\n\n\n\n<li>Enqueue every <code>(r, c, dist=0)<\/code> for which <code>mat[r][c] == 0<\/code> and mark visited.<\/li>\n\n\n\n<li>While the queue isn\u2019t empty:\n<ul class=\"wp-block-list\">\n<li>Pop <code>(i, j, d)<\/code>, set <code>distance[i][j] = d<\/code>.<\/li>\n\n\n\n<li>For each neighbor <code>(ni, nj)<\/code> in four directions:\n<ul class=\"wp-block-list\">\n<li>If it\u2019s in bounds and unvisited, enqueue <code>(ni, nj, d+1)<\/code> and mark visited.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Return <code>distance<\/code>.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-code-implementation\">Code Implementation<\/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\nfrom typing import List\n\nclass Solution:\n    def updateMatrix(self, mat: List[List[int]]) -&gt; List[List[int]]:\n        rows, cols = len(mat), len(mat[0])\n        visited = [[0]*cols for _ in range(rows)]\n        distance = [[0]*cols for _ in range(rows)]\n        queue = deque()\n\n        # 1. Enqueue all zeros as BFS sources\n        for r in range(rows):\n            for c in range(cols):\n                if mat[r][c] == 0:\n                    queue.append((r, c, 0))\n                    visited[r][c] = 1\n\n        # 2. BFS from all zeros simultaneously\n        while queue:\n            i, j, d = queue.popleft()\n            distance[i][j] = d\n            # Visit four directions\n            for di, dj in [(-1,0),(1,0),(0,-1),(0,1)]:\n                ni, nj = i + di, j + dj\n                # Skip out of bounds or already visited\n                if (0 &lt;= ni &lt; rows and 0 &lt;= nj &lt; cols \n                        and visited[ni][nj] == 0):\n                    visited[ni][nj] = 1\n                    queue.append((ni, nj, d+1))\n\n        return distance\" 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 style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> typing <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> List<\/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\">updateMatrix<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">mat<\/span><span style=\"color: #D4D4D4\">: List[List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]]) -&gt; List[List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        rows, cols = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(mat), <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(mat[<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">])<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        visited = [[<\/span><span style=\"color: #B5CEA8\">0<\/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\">        distance = [[<\/span><span style=\"color: #B5CEA8\">0<\/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 zeros as BFS sources<\/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\"> mat[r][c] == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    queue.append((r, c, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">))<\/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 from all zeros simultaneously<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> queue:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            i, j, d = queue.popleft()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            distance[i][j] = d<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># Visit four directions<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> di, dj <\/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\">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\">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\">                ni, nj = i + di, j + dj<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Skip out of bounds or already visited<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> (<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> &lt;= ni &lt; rows <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> &lt;= nj &lt; cols <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                        <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> visited[ni][nj] == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    visited[ni][nj] = <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    queue.append((ni, nj, d+<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">))<\/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\"> distance<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"3-step-by-step-explanation\">Step-by-Step Explanation<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Initialization:<\/strong>\n<ul class=\"wp-block-list\">\n<li><code>visited[r][c]<\/code> tracks which cells have been enqueued.<\/li>\n\n\n\n<li><code>distance[r][c]<\/code> will hold the answer for each cell.<\/li>\n\n\n\n<li><code>queue<\/code> is seeded with all <code>(r, c, 0)<\/code> where <code>mat[r][c] == 0<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Multi-Source BFS:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Each dequeued tuple gives us <code>(i, j)<\/code> plus its distance <code>d<\/code> from the nearest zero.<\/li>\n\n\n\n<li>We record <code>distance[i][j] = d<\/code>.<\/li>\n\n\n\n<li>For each neighbor <code>(ni, nj)<\/code>, if it\u2019s in bounds and not yet visited, we enqueue <code>(ni, nj, d+1)<\/code>\u2014one step farther from a zero.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Completion:<\/strong>\n<ul class=\"wp-block-list\">\n<li>When BFS finishes, every cell\u2019s shortest distance to some zero has been set.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"4-dry-run-example\">Dry Run Example<\/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=\"mat = [\n  [0,1,1],\n  [1,1,1],\n  [1,1,0]\n]\" 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: #D4D4D4\">mat = [<\/span><\/span>\n<span class=\"line\"><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>\n<span class=\"line\"><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\">1<\/span><span style=\"color: #D4D4D4\">],<\/span><\/span>\n<span class=\"line\"><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>\n<span class=\"line\"><span style=\"color: #D4D4D4\">]<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Enqueue zeros:<\/strong> <code>(0,0,0)<\/code> and <code>(2,2,0)<\/code>.<\/li>\n\n\n\n<li><strong>BFS Level 0:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Dequeue <code>(0,0,0)<\/code>, set <code>dist[0][0]=0<\/code>, enqueue its unvisited neighbors <code>(1,0,1)<\/code> and <code>(0,1,1)<\/code>.<\/li>\n\n\n\n<li>Dequeue <code>(2,2,0)<\/code>, set <code>dist[2][2]=0<\/code>, enqueue <code>(1,2,1)<\/code> and <code>(2,1,1)<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>BFS Level 1:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Process <code>(1,0,1)<\/code>, <code>(0,1,1)<\/code>, <code>(1,2,1)<\/code>, <code>(2,1,1)<\/code>\u2014set distances to 1 and enqueue their fresh neighbors with <code>d=2<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>BFS Level 2:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Remaining cell <code>(1,1,2)<\/code> gets distance 2.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Result:<\/strong> csharpCopy<code>[ [0,1,2], [1,2,1], [2,1,0] ]<\/code><\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5-time-amp-space-complexity\">Time &amp; Space Complexity<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong> O(m\u00b7n)\n<ul class=\"wp-block-list\">\n<li>Each cell is enqueued and processed at most once.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong> O(m\u00b7n)\n<ul class=\"wp-block-list\">\n<li>The <code>visited<\/code> and <code>distance<\/code> arrays plus the BFS queue may all hold O(m\u00b7n) elements in the worst case.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6-conclusion\">Conclusion<\/h2>\n\n\n\n<p>By turning every zero into a BFS source and expanding outward, we compute every cell\u2019s distance to the nearest zero in optimal linear time. This \u201cmulti-source BFS\u201d pattern is a powerful tool for any grid problem that asks for nearest distances to a set of starting points. 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 solve the \u201c01 Matrix\u201d problem (LeetCode 542) by using a multi-source breadth-first search. We walk through the Python code, explain each step, run a dry example, and analyze complexity. What the Problem Asks LeetCode 542: 01 MatrixGiven an m x n binary matrix mat of 0s and 1s, return a matrix dist<\/p>\n","protected":false},"author":1,"featured_media":165,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,5],"tags":[17],"class_list":{"0":"post-160","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"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/05\/01-matrix-lleetcode-542-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\/160","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=160"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/160\/revisions"}],"predecessor-version":[{"id":170,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/160\/revisions\/170"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/165"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=160"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=160"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=160"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}