{"id":112,"date":"2026-11-13T12:31:38","date_gmt":"2026-11-13T04:31:38","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-0-1-bfs-uses-a-deque-for-weights-zero-and-one\/"},"modified":"2026-11-13T21:50:35","modified_gmt":"2026-11-13T13:50:35","slug":"how-0-1-bfs-uses-a-deque-for-weights-zero-and-one","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-0-1-bfs-uses-a-deque-for-weights-zero-and-one\/","title":{"rendered":"How 0-1 BFS uses a deque for weights zero and one"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>0-1 BFS<\/strong> computes shortest paths when every edge weight is <strong>0 or 1<\/strong>. A relaxation of weight 0 pushes the neighbor at the <strong>front<\/strong> of a deque, and a relaxation of weight 1 pushes it at the <strong>back<\/strong>. The front of the deque stays in distance order, so each vertex is settled in linear time, <strong>O(V+E)<\/strong>. It is Dijkstra for this weight set, with the heap replaced by the two ends of a deque.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">A binary heap spends a logarithm to find the next smallest tentative distance. If an edge can increase the distance by only 0 or 1, the frontier never contains a gap wider than 1. Vertices at the current distance belong in front of vertices at the current distance plus one. A deque expresses exactly those two buckets.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Pushing a zero-weight improvement to the front keeps it with the current distance. Pushing a one-weight improvement to the back schedules it after every vertex that is already one closer. No other weight is allowed to use either end.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">On a graph whose weights are only 0 and 1, the algorithm returns true shortest paths and runs in O(V+E), because each vertex is enqueued a constant number of times when a settled vertex is not reprocessed. Extra memory is the deque and the distance array. The same proof as Dijkstra applies: the front vertex has the minimum tentative distance.<\/p>\n\n\n<p class=\"wp-block-paragraph\">A weight of 2 or more, pushed as if it were 1, lands in the wrong bucket and can be settled too early. Dial&#8217;s algorithm is the generalization that keeps a bucket per integer residue when weights are small integers up to C. Ordinary BFS is the special case in which every weight is 1, so the front push never happens and a queue suffices.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Set dist[source] = 0 and every other distance to infinity. Push the source on a deque.<\/li>\n<li>Pop u from the front. If u was already settled at a better distance, skip it.<\/li>\n<li>For an edge u\u2192v of weight w in {0, 1}, if dist[u]+w &lt; dist[v], update dist[v] and parent[v].<\/li>\n<li>If w = 0, push v at the front. If w = 1, push v at the back.<\/li>\n<li>Continue until the deque is empty. The parent pointers are a shortest-path tree.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The linear bound is for weights in {0, 1}. Arbitrary nonnegative weights need a heap. Small integer weights up to a bound C need Dial&#8217;s buckets. Negative weights need Bellman-Ford. Treating a general graph as 0-1 by clamping weights produces distances for a different graph.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when a weight is neither zero nor one<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Push every improved neighbor to the back<\/td>\n<td>A zero-weight edge then waits behind vertices that are farther away. The pop order is no longer distance order unless every weight is 1.<\/td>\n<\/tr>\n<tr>\n<td>Push a weight-2 edge to the back as though it cost 1<\/td>\n<td>The neighbor&#8217;s true distance is not the current distance plus one. Later pops can be wrong.<\/td>\n<\/tr>\n<tr>\n<td>Use the deque on negative weights<\/td>\n<td>A negative edge can improve a vertex that already left the deque. The algorithm does not reopen settled structure the way a correct negative-edge algorithm must.<\/td>\n<\/tr>\n<tr>\n<td>Quote O(V+E) for Dial&#8217;s algorithm on weights up to C<\/td>\n<td>Dial&#8217;s cost grows with C. The deque bound is the C = 1 case.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Equal positive weights belong to breadth-first search. General nonnegative weights belong to Dijkstra. Integer weights bounded by a small C belong to Dial&#8217;s algorithm.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The Bash script and the Python script run 0-1 BFS. A weight-0 edge enters the front of the deque and a weight-1 edge enters the back. Edges: 0\u21921 weight 0, 0\u21922 weight 1, 1\u21922 weight 1, 1\u21923 weight 0, 2\u21923 weight 1. Both print <code>0 0 1 0<\/code>.<\/p>\n\n<pre><code class=\"language-bash\"># neighbor lists and parallel weight lists, weights 0 or 1\nnb=(&quot;1 2&quot; &quot;2 3&quot; &quot;3&quot; &quot;&quot;)\nwt=(&quot;0 1&quot; &quot;1 0&quot; &quot;1&quot; &quot;&quot;)\ndist=(0 1000000000 1000000000 1000000000)\n# deque stored in an array with a moving head; appendleft writes in front of head\nq=(0)\nhead=0\nwhile (( head &lt; ${#q[@]} )); do\n  u=${q[head]}\n  head=$((head+1))\n  set -- ${nb[u]}\n  ws=(${wt[u]})\n  k=0\n  for v in &quot;$@&quot;; do\n    w=${ws[k]}\n    k=$((k+1))\n    nd=$((dist[u]+w))\n    if (( nd &lt; dist[v] )); then\n      dist[v]=$nd\n      if (( w == 0 )); then\n        # rebuild with v at the front of the remaining queue\n        rest=(&quot;${q[@]:head}&quot;)\n        q=(&quot;$v&quot; &quot;${rest[@]}&quot;)\n        head=0\n      else\n        q+=(&quot;$v&quot;)\n      fi\n    fi\n  done\ndone\necho &quot;${dist[*]}&quot;\n<\/code><\/pre>\n<pre><code class=\"language-python\">from collections import deque\n\n# (neighbor, weight) with weights in {0, 1}\nadj = [[(1, 0), (2, 1)], [(2, 1), (3, 0)], [(3, 1)], []]\ndist = [10**9] * 4\ndist[0] = 0\ndq = deque([0])\nwhile dq:\n    u = dq.popleft()\n    for v, w in adj[u]:\n        nd = dist[u] + w\n        if nd &lt; dist[v]:\n            dist[v] = nd\n            if w == 0:\n                dq.appendleft(v)\n            else:\n                dq.append(v)\nassert dist == [0, 0, 1, 0]\nprint(*dist)\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">A <strong>0-1 BFS<\/strong> is the shortest-path walk for edges whose weights are only 0 and 1, such as a maze with free steps and costly steps. Production routers with a wider integer range use Dial&#8217;s buckets or Dijkstra. The deque trick is the same idea squeezed to two weights.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop 0-1 BFS when any weight leaves {0, 1}. Use Dijkstra, or Dial if the weights are small integers. Keep the deque when the graph really is a 0-1 graph, including state graphs where a move is either free or costs one.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for 0-1 BFS returns the front push for weight 0 and the back push for weight 1. <strong>0-1 BFS is Dijkstra for weights in {0, 1}, implemented as a deque that pushes a zero-weight relaxation to the front and a one-weight relaxation to the back.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: 0-1 BFS computes shortest paths when every edge weight is 0 or 1. A relaxation of weight 0 pushes the neighbor at the front of a deque, and a relaxation of weight 1 pushes it at the back. The front of the deque stays in distance order,&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,32],"tags":[],"class_list":["post-112","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-graphs"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/112","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=112"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/112\/revisions"}],"predecessor-version":[{"id":511,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/112\/revisions\/511"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=112"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=112"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=112"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}