{"id":633,"date":"2026-06-15T11:43:00","date_gmt":"2026-06-15T11:43:00","guid":{"rendered":"https:\/\/hyc.eshachem.com\/program\/?page_id=633"},"modified":"2026-06-15T11:45:25","modified_gmt":"2026-06-15T11:45:25","slug":"data-structures-and-algorithms-stack-recursion-dp-backtracking","status":"publish","type":"page","link":"https:\/\/hyc.eshachem.com\/program\/technical-articles\/data-structures-and-algorithms-stack-recursion-dp-backtracking\/","title":{"rendered":"Data Structures and Algorithms\u00a0: Stack, Recursion &#8211; DP &amp; Backtracking"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">I went to the CPE yesterday and was shocked! The questions were all in English and focused entirely on algorithms. Because of this, I\u2019ve decided to start an \u2018algorithm journey\u2019 and document my thoughts in English.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Today\u2019s topic is <strong>Stacks<\/strong>. While it is a basic data structure, it is also used in some of the <strong>most difficult<\/strong> algorithms. Today, I will <strong>dive into<\/strong> the stack and explain how it works with a specific algorithm.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"stack\">Stack<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A stack is an <strong>Abstract Data Type (ADT)<\/strong> that follows the <strong>LIFO (Last-In, First-Out)<\/strong> principle. Because it is an ADT, it can be implemented using different data structures in various programming languages. For example, in Python, we can use a <code><strong>list<\/strong><\/code><strong> <\/strong>or <code><strong>linked list<\/strong><\/code><strong> <\/strong>to implement a stack, while in C++, we can use the<code><strong>std::stack<\/strong><\/code> container.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Python:<\/strong> Using <code>list.append()<\/code> and <code>list.pop()<\/code> is the most common way to simulate a stack.<\/li>\n\n\n\n<li><strong>C++:<\/strong> Using <code>#include &lt;stack&gt;<\/code> is highly optimized and preferred.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">We can solve the following problems using a <strong>Stack<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Fibonacci Sequence<\/strong><\/li>\n\n\n\n<li><strong>Tower of Hanoi<\/strong><\/li>\n\n\n\n<li><strong>Maze<\/strong><\/li>\n\n\n\n<li><strong>Eight Queens<\/strong><\/li>\n\n\n\n<li><strong>Infix, Prefix, Postfix<\/strong><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"recursion\">Recursion<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">the most famous algorithm concept associated with the stack is <strong>Recursion<\/strong>.<strong> <\/strong>By definition, recursion requires two core components:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>a <strong>self-referential process<\/strong> (a <strong>loop<\/strong>-like structure)<\/li>\n\n\n\n<li>a <strong>base case<\/strong> (the <strong>exit <\/strong>condition) to terminate the process<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Recursion can be categorized into <strong>Direct <\/strong>and <strong>Indirect<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Direct Recursion<\/strong>\u00a0: this occurs when a function explicitly calls it self within ite own body.<\/li>\n<\/ul>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">def Fun():\n  ...\n  if (...):\n    Fun()<\/code><\/span><\/pre>\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Indirect Recursion\u00a0: <\/strong>this occurs when a function calls a second function, which then calls the original function, creating a circular call chain.<\/li>\n<\/ul>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">def Fun1():\n  ...\n  if (...):\n    Fun2()\n\ndef Fun2():\n  ...\n  if (...):\n    Fun1()<\/code><\/span><\/pre>\n\n\n<h4 class=\"wp-block-heading\" id=\"fibonacci-sequence\"><strong>Fibonacci S<\/strong>equence<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Fibonacci Sequence is a classical recursion problem defined by the recurrence relation <code>A[n] = A[n-1] + A[n-2]<\/code>.Recursion is most <strong>effective <\/strong>when the current solution relies on the result if previously computed subproblems.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">def fib(n):\n    <span class=\"hljs-comment\"># Base cases: F(0) = 0, F(1) = 1<\/span>\n    <span class=\"hljs-keyword\">if<\/span> n &lt;= <span class=\"hljs-number\">1<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> n\n    <span class=\"hljs-comment\"># Recursive step<\/span>\n    <span class=\"hljs-keyword\">else<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> fib(n - <span class=\"hljs-number\">1<\/span>) + fib(n - <span class=\"hljs-number\">2<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h4 class=\"wp-block-heading\" id=\"tower-of-hanoi\">Tower of\u00a0Hanoi<\/h4>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn-images-1.medium.com\/max\/880\/1*kZANXFtPMEf9BO1Yn-2CAQ@2x.jpeg\" alt=\"\"><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The Tower of Hanoi is an <strong>ancient <\/strong>mathematical puzzle.While the detailed rules are well-known the recursion is the most<strong> elegant <\/strong>way to solve it. if you divide the process into sub-step, you will notice the fowlloing pattern:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>step-1: move the top <code>n-1<\/code> disks from <strong>Source<\/strong> (Stick 1) to <strong>Auxiliary<\/strong> (Stick 2).<\/li>\n\n\n\n<li>step-2: move the largest disk <code>n<\/code> from <strong>Source<\/strong> (Stick 1) to <strong>Destination<\/strong> (Stick 3).<\/li>\n\n\n\n<li>step-3:move the <code>n-1<\/code> disks from <strong>Auxiliary<\/strong> (Stick 2) to <strong>Destination<\/strong> (Stick 3).<\/li>\n<\/ul>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">def hanoi(n, source, target, auxiliary):\n    <span class=\"hljs-comment\"># Base Case<\/span>\n    <span class=\"hljs-keyword\">if<\/span> n == <span class=\"hljs-number\">1<\/span>:\n        <span class=\"hljs-keyword\">print<\/span>(f<span class=\"hljs-string\">\"Move disk 1 from {source} to {target}\"<\/span>)\n        <span class=\"hljs-keyword\">return<\/span>\n    \n    <span class=\"hljs-comment\"># Step 1: move the top n-1 disks<\/span>\n    hanoi(n - <span class=\"hljs-number\">1<\/span>, source, auxiliary, target)\n    \n    <span class=\"hljs-comment\"># Step 2: move the largest disk n<\/span>\n    <span class=\"hljs-keyword\">print<\/span>(f<span class=\"hljs-string\">\"Move disk {n} from {source} to {target}\"<\/span>)\n    \n    <span class=\"hljs-comment\"># Step 3: move the n-1 disks<\/span>\n    hanoi(n - <span class=\"hljs-number\">1<\/span>, auxiliary, target, source)\n\nhanoi(<span class=\"hljs-number\">3<\/span>, <span class=\"hljs-string\">'A'<\/span>, <span class=\"hljs-string\">'C'<\/span>, <span class=\"hljs-string\">'B'<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\" id=\"dynamic-programming\">Dynamic Programming<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>DP (Dynamic Programming)<\/strong> is a widely-used method which is based on the <strong>Divide-and-Conquer<\/strong> strategy\u00a0, often implemented using recursion. Nevertheless the DP can slove much more complex problem by <strong>recording previous result<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, if you use standard recursion to solve the <strong>Fibonacci Sequence<\/strong>, the process slows down significantly (or even crashes) when <code>n&gt;100<\/code>, In contrast, a DP approach remains <strong>efficient <\/strong>because it <strong>avoids recomputing<\/strong> the same subproblems repeatedly.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">def fib_memo(n, memo={}):\n    <span class=\"hljs-keyword\">if<\/span> n <span class=\"hljs-keyword\">in<\/span> memo:\n        <span class=\"hljs-keyword\">return<\/span> memo[n]\n    <span class=\"hljs-keyword\">if<\/span> n &lt;= <span class=\"hljs-number\">1<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> n\n    \n    memo[n] = fib_memo(n - <span class=\"hljs-number\">1<\/span>, memo) + fib_memo(n - <span class=\"hljs-number\">2<\/span>, memo)\n    <span class=\"hljs-keyword\">return<\/span> memo[n]<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\" id=\"backtracking\"><strong>Backtracking<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Backtracking <\/strong>is an advanced<strong> <\/strong>algorithm (based on the <strong>Enumeration method)<\/strong> that uses recursion to solve problem like the <strong>Maze<\/strong> and the<strong> Eight Queens<\/strong>. It works by incrementally building a solution and<strong> \u2018backing-tracking\u2019 <\/strong>(returning to a previous state) as soon as it determines that the current path cannot lead to a valid solution.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"maze\">Maze<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">I think everyone has seen Short showing robot races through a maze, how do these robots solve a maze so quickly? The secret is likely <strong>Backtracking<\/strong>! (Actually is DFS, but that\u2019s another story)<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">How is the backtracking implemented int the program? <strong>we can <\/strong>examine the process as follows<strong>:<\/strong><\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">def solve_maze(maze, x, y, solution):\n    <span class=\"hljs-comment\"># 1. Base Case<\/span>\n    <span class=\"hljs-keyword\">if<\/span> x == len(maze) - <span class=\"hljs-number\">1<\/span> <span class=\"hljs-keyword\">and<\/span> y == len(maze[<span class=\"hljs-number\">0<\/span>]) - <span class=\"hljs-number\">1<\/span>:\n        solution[x][y] = <span class=\"hljs-number\">1<\/span>\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">True<\/span>\n\n    <span class=\"hljs-comment\"># 2. Validation: Ensure the current cell is within bounds, not a wall, and unvisited<\/span>\n    <span class=\"hljs-keyword\">if<\/span> <span class=\"hljs-number\">0<\/span> &lt;= x &lt; len(maze) <span class=\"hljs-keyword\">and<\/span> <span class=\"hljs-number\">0<\/span> &lt;= y &lt; len(maze[<span class=\"hljs-number\">0<\/span>]) <span class=\"hljs-keyword\">and<\/span> maze[x][y] == <span class=\"hljs-number\">0<\/span> <span class=\"hljs-keyword\">and<\/span> solution[x][y] == <span class=\"hljs-number\">0<\/span>:\n        <span class=\"hljs-comment\"># mark the path<\/span>\n        solution[x][y] = <span class=\"hljs-number\">1<\/span>\n        \n        <span class=\"hljs-comment\"># 3. recursion<\/span>\n        <span class=\"hljs-keyword\">if<\/span> (solve_maze(maze, x + <span class=\"hljs-number\">1<\/span>, y, solution) <span class=\"hljs-keyword\">or<\/span> \n            solve_maze(maze, x - <span class=\"hljs-number\">1<\/span>, y, solution) <span class=\"hljs-keyword\">or<\/span> \n            solve_maze(maze, x, y + <span class=\"hljs-number\">1<\/span>, solution) <span class=\"hljs-keyword\">or<\/span> \n            solve_maze(maze, x, y - <span class=\"hljs-number\">1<\/span>, solution)):\n            <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">True<\/span>\n        \n        <span class=\"hljs-comment\"># 4. Backtracking: if no direction leads to the exit , unmark this cell<\/span>\n        solution[x][y] = <span class=\"hljs-number\">0<\/span>\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">False<\/span>\n\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">False<\/span>\n<span class=\"hljs-comment\"># 0 for path, 1 for wall<\/span>\nmaze = [\n    [<span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">0<\/span>],\n    [<span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">1<\/span>],\n    [<span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">1<\/span>],\n    [<span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">0<\/span>]\n]\n\n<span class=\"hljs-comment\"># Initialize a visited matrix of the same dimensions as the maze.<\/span>\nsolution = [[<span class=\"hljs-number\">0<\/span> <span class=\"hljs-keyword\">for<\/span> _ in range(len(maze[<span class=\"hljs-number\">0<\/span>]))] <span class=\"hljs-keyword\">for<\/span> _ in range(len(maze))]\n\n<span class=\"hljs-comment\"># \u5f9e\u8d77\u9ede (0, 0) \u958b\u59cb\u547c\u53eb<\/span>\n<span class=\"hljs-keyword\">if<\/span> solve_maze(maze, <span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">0<\/span>, solution):\n    <span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"\u627e\u5230\u4e86\u8def\u5f91\uff01\"<\/span>)\n    <span class=\"hljs-keyword\">for<\/span> row in solution:\n        <span class=\"hljs-keyword\">print<\/span>(row)\n<span class=\"hljs-keyword\">else<\/span>:\n    <span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"\u627e\u4e0d\u5230\u51fa\u53e3\u3002\"<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h4 class=\"wp-block-heading\" id=\"eight-queens\"><strong>Eight Queens<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The Eight Queens puzzle is a classical mathematical problem that is best solved using <strong>Backtracking<\/strong>.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">placing eight chess queens on an 8\u00d78 chessboard so that no two queens threaten each\u00a0other.<\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">if you attempted to use <strong>Brute Force<\/strong>,it would be nearly impossible! Choosing 8 positions out of 64 results in<strong> 4,426,165,368<\/strong> combinations! However we can simplify the problem by using a key characteristic<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>each row can only contain exactly one queen<\/strong>.<\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">By dividing the problem into a recursive process, we only need to find a valid column for the queen in each row.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">def is_safe(board, row, col):\n    <span class=\"hljs-comment\"># Validation : Checks for column and diagonal conflicts.<\/span>\n    <span class=\"hljs-keyword\">for<\/span> i in range(row):\n        <span class=\"hljs-comment\"># Check for diagonal conflict: |row_diff| == |col_diff|<\/span>\n        <span class=\"hljs-keyword\">if<\/span> board[i] == col <span class=\"hljs-keyword\">or<\/span> abs(board[i] - col) == abs(i - row):\n            <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">False<\/span>\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">True<\/span>\n\ndef solve_queens(board, row):\n    <span class=\"hljs-comment\"># Base Case<\/span>\n    <span class=\"hljs-keyword\">if<\/span> row == len(board):\n        <span class=\"hljs-keyword\">print<\/span>(board)\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">True<\/span>\n\n    <span class=\"hljs-keyword\">for<\/span> col in range(len(board)):\n        <span class=\"hljs-keyword\">if<\/span> is_safe(board, row, col):\n            board[row] = col\n            \n            <span class=\"hljs-comment\"># Recursive Step<\/span>\n            solve_queens(board, row + <span class=\"hljs-number\">1<\/span>)\n            \n            <span class=\"hljs-comment\"># Backtracking: Implicitly handled by overwriting board[row] <\/span>\n            <span class=\"hljs-comment\"># in the next iteration of the loop.<\/span>\n            \n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">False<\/span>\n\nn = <span class=\"hljs-number\">8<\/span>\nboard = [<span class=\"hljs-number\">0<\/span>] * n\nsolve_queens(board, <span class=\"hljs-number\">0<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\" id=\"summarize\">Summarize<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Today, I explored the concept of stacks and how recursive algorithms are built upon them. I also analyzed several classic problems that utilize these techniques. However today I have only <strong>scratch the surface, <\/strong>Each of the problems we discussed today deserves its own <strong>dedicated article<\/strong>.<strong> My algorithm journey <\/strong>is just beginning, so\u2026 <strong>stay tuned!!<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>I went to the CPE yesterday and was shocked! The questions were all in English and focused entirely on algorithms. Because of this, I\u2019ve decided to start an \u2018algorithm journey\u2019 and document my thoughts in English. Today\u2019s topic is Stacks. While it is a basic data structure, it is also used in some of the [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"parent":440,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"class_list":["post-633","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/hyc.eshachem.com\/program\/wp-json\/wp\/v2\/pages\/633","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hyc.eshachem.com\/program\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/hyc.eshachem.com\/program\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/hyc.eshachem.com\/program\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hyc.eshachem.com\/program\/wp-json\/wp\/v2\/comments?post=633"}],"version-history":[{"count":2,"href":"https:\/\/hyc.eshachem.com\/program\/wp-json\/wp\/v2\/pages\/633\/revisions"}],"predecessor-version":[{"id":635,"href":"https:\/\/hyc.eshachem.com\/program\/wp-json\/wp\/v2\/pages\/633\/revisions\/635"}],"up":[{"embeddable":true,"href":"https:\/\/hyc.eshachem.com\/program\/wp-json\/wp\/v2\/pages\/440"}],"wp:attachment":[{"href":"https:\/\/hyc.eshachem.com\/program\/wp-json\/wp\/v2\/media?parent=633"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}