{"id":26679,"date":"2017-12-22T19:51:38","date_gmt":"2017-12-22T14:21:38","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26679"},"modified":"2017-12-22T19:51:38","modified_gmt":"2017-12-22T14:21:38","slug":"branch-bound-8-puzzle-problem","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/branch-bound-8-puzzle-problem\/","title":{"rendered":"Branch and Bound | Set 3 (8 puzzle Problem)"},"content":{"rendered":"<p>We have introduced Branch and Bound and discussed 0\/1 Knapsack problem in below posts.<\/p>\n<ul>\n<li><a href=\"http:\/\/www.geeksforgeeks.org\/branch-and-bound-set-1-introduction-with-01-knapsack\/\" target=\"_blank\" rel=\"noopener\">Branch and Bound | Set 1 (Introduction with 0\/1 Knapsack)<\/a><\/li>\n<li><a href=\"http:\/\/www.geeksforgeeks.org\/branch-and-bound-set-2-implementation-of-01-knapsack\/\" target=\"_blank\" rel=\"noopener\">Branch and Bound | Set 2 (Implementation of 0\/1 Knapsack)<\/a><\/li>\n<\/ul>\n<p>In this puzzle solution of 8 puzzle problem is discussed.<br \/>\n<em>Given a 3\u00d73 board with 8 tiles (every tile has one number from 1 to 8) and one empty space. The objective is to place the numbers on tiles to match final configuration using the empty space. We can slide four adjacent (left, right, above and below) tiles into the empty space.<br \/>\n<\/em><br \/>\nFor example,<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-26688\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/8puzzle2-300x119.png\" alt=\"Branch and Bound | Set 3 (8 puzzle Problem\" width=\"300\" height=\"119\" \/><\/p>\n<p><strong>1. DFS (Brute-Force)<\/strong><br \/>\nWe can perform depth-first search on state space (Set of all configurations of a given problem i.e. all states that can be reached from initial state) tree.<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-26689\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/image6.png\" alt=\"Branch and Bound | Set 3 (8 puzzle Problem)\" width=\"451\" height=\"289\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/image6.png 451w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/image6-300x192.png 300w\" sizes=\"(max-width: 451px) 100vw, 451px\" \/><\/p>\n<p>state space tree for 8 puzzle<\/p>\n<p>&nbsp;<\/p>\n<p>In this solution, successive moves can take us away from the goal rather than bringing closer. The search of state space tree follows leftmost path from the root regardless of initial state. An answer node may never be found in this approach.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>2. BFS (Brute-Force)<\/strong><br \/>\nWe can perform a Breadth-first search on state space tree. This always finds a goal state nearest to the root. But no matter what the initial state is, the algorithm attempts the same sequence of moves like DFS.<\/p>\n<p><strong>3. Branch and Bound<\/strong><br \/>\nThe search for an answer node can often be speeded by using an \u201cintelligent\u201d ranking function, also called an approximate cost function to avoid searching in sub-trees that do not contain an answer node. It is similar to backtracking technique but uses BFS-like search.<\/p>\n<p>There are basically three types of nodes involved in Branch and Bound<br \/>\n<strong>1. Live node<\/strong> is a node that has been generated but whose children have not yet been generated.<br \/>\n<strong>2. E-node<\/strong> is a live node whose children are currently being explored. In other words, an E-node is a node currently being expanded.<br \/>\n<strong>3. Dead node <\/strong>is a generated node that is not to be expanded or explored any further. All children of a dead node have already been expanded.<\/p>\n<p>Cost function:<br \/>\nEach node X in the search tree is associated with a cost. The cost function is useful for determining the next E-node. The next E-node is the one with least cost. The cost function is defined as,<\/p>\n<pre>   C(X) = g(X) + h(X) where\r\n   g(X) = cost of reaching the current node \r\n          from the root\r\n   h(X) = cost of reaching an answer node from X.<\/pre>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Ideal Cost function for 8-puzzle Algorithm : <\/strong><br \/>\nWe assume that moving one tile in any direction will have 1 unit cost. Keeping that in mind, we define cost function for 8-puzzle algorithm as below :<\/p>\n<pre>   c(x) = f(x) + h(x) where\r\n   f(x) is the length of the path from root to x \r\n        (the number of moves so far) and\r\n   h(x) is the number of non-blank tiles not in \r\n        their goal position (the number of mis-\r\n        -placed tiles). There are at least h(x) \r\n        moves to transform state x to a goal state<\/pre>\n<p>An algorithm is available for getting an approximation of h(x) which is a unknown value.<\/p>\n<p><strong>Complete Algorithm:<\/strong><\/p>\n<pre>\/* Algorithm LCSearch uses c(x) to find an answer node\r\n * LCSearch uses Least() and Add() to maintain the list \r\n   of live nodes\r\n * Least() finds a live node with least c(x), deletes\r\n   it from the list and returns it\r\n * Add(x) adds x to the list of live nodes\r\n * Implement list of live nodes as a min heap *\/\r\n\r\nstruct list_node\r\n{\r\n   list_node *next;\r\n\r\n   \/\/ Helps in tracing path when answer is found\r\n   list_node *parent; \r\n   float cost;\r\n} \r\n\r\nalgorithm LCSearch(list_node *t)\r\n{\r\n   \/\/ Search t for an answer node\r\n   \/\/ Input: Root node of tree t\r\n   \/\/ Output: Path from answer node to root\r\n   if (*t is an answer node)\r\n   {\r\n       print(*t);\r\n       return;\r\n   }\r\n   \r\n   E = t; \/\/ E-node\r\n\r\n   Initialize the list of live nodes to be empty;\r\n   while (true)\r\n   {\r\n      for each child x of E\r\n      {\r\n          if x is an answer node\r\n          {\r\n             print the path from x to t;\r\n             return;\r\n          }\r\n          Add (x); \/\/ Add x to list of live nodes;\r\n          x-&gt;parent = E; \/\/ Pointer for path to root\r\n      }\r\n\r\n      if there are no more live nodes\r\n      {\r\n         print (\"No answer node\");\r\n         return;\r\n      }\r\n       \r\n      \/\/ Find a live node with least estimated cost\r\n      E = Least(); \r\n\r\n      \/\/ The found node is deleted from the list of \r\n      \/\/ live nodes\r\n   }\r\n}\r\n<\/pre>\n<p>Below diagram shows the path followed by above algorithm to reach final configuration from given initial configuration of 8-Puzzle. Note that only nodes having least value of cost function are expanded.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-26693\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/15-Puzzle.png\" alt=\"Branch and Bound | Set 3 (8 puzzle Problem)\" width=\"654\" height=\"580\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/15-Puzzle.png 654w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/15-Puzzle-300x266.png 300w\" sizes=\"(max-width: 654px) 100vw, 654px\" \/><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ Program to print path from root node to destination node<br\/>\/\/ for N*N -1 puzzle algorithm using Branch and Bound<br\/>\/\/ The solution assumes that instance of puzzle is solvable<br\/>#include &lt;bits\/stdc++.h&gt;<br\/>using namespace std;<br\/>#define N 3<br\/> <br\/>\/\/ state space tree nodes<br\/>struct Node<br\/>{<br\/>    \/\/ stores parent node of current node<br\/>    \/\/ helps in tracing path when answer is found<br\/>    Node* parent;<br\/> <br\/>    \/\/ stores matrix<br\/>    int mat[N][N];<br\/> <br\/>    \/\/ stores blank tile cordinates<br\/>    int x, y;<br\/> <br\/>    \/\/ stores the number of misplaced tiles<br\/>    int cost;<br\/> <br\/>    \/\/ stores the number of moves so far<br\/>    int level;<br\/>};<br\/> <br\/>\/\/ Function to print N x N matrix<br\/>int printMatrix(int mat[N][N])<br\/>{<br\/>    for (int i = 0; i &lt; N; i++)<br\/>    {<br\/>        for (int j = 0; j &lt; N; j++)<br\/>            printf(&quot;%d &quot;, mat[i][j]);<br\/>        printf(&quot;\\n&quot;);<br\/>    }<br\/>}<br\/> <br\/>\/\/ Function to allocate a new node<br\/>Node* newNode(int mat[N][N], int x, int y, int newX,<br\/>              int newY, int level, Node* parent)<br\/>{<br\/>    Node* node = new Node;<br\/> <br\/>    \/\/ set pointer for path to root<br\/>    node-&gt;parent = parent;<br\/> <br\/>    \/\/ copy data from parent node to current node<br\/>    memcpy(node-&gt;mat, mat, sizeof node-&gt;mat);<br\/> <br\/>    \/\/ move tile by 1 postion<br\/>    swap(node-&gt;mat[x][y], node-&gt;mat[newX][newY]);<br\/> <br\/>    \/\/ set number of misplaced tiles<br\/>    node-&gt;cost = INT_MAX;<br\/> <br\/>    \/\/ set number of moves so far<br\/>    node-&gt;level = level;<br\/> <br\/>    \/\/ update new blank tile cordinates<br\/>    node-&gt;x = newX;<br\/>    node-&gt;y = newY;<br\/> <br\/>    return node;<br\/>}<br\/> <br\/>\/\/ botton, left, top, right<br\/>int row[] = { 1, 0, -1, 0 };<br\/>int col[] = { 0, -1, 0, 1 };<br\/> <br\/>\/\/ Function to calculate the the number of misplaced tiles<br\/>\/\/ ie. number of non-blank tiles not in their goal position<br\/>int calculateCost(int initial[N][N], int final[N][N])<br\/>{<br\/>    int count = 0;<br\/>    for (int i = 0; i &lt; N; i++)<br\/>      for (int j = 0; j &lt; N; j++)<br\/>        if (initial[i][j] &amp;&amp; initial[i][j] != final[i][j])<br\/>           count++;<br\/>    return count;<br\/>}<br\/> <br\/>\/\/ Function to check if (x, y) is a valid matrix cordinate<br\/>int isSafe(int x, int y)<br\/>{<br\/>    return (x &gt;= 0 &amp;&amp; x &lt; N &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; N);<br\/>}<br\/> <br\/>\/\/ print path from root node to destination node<br\/>void printPath(Node* root)<br\/>{<br\/>    if (root == NULL)<br\/>        return;<br\/>    printPath(root-&gt;parent);<br\/>    printMatrix(root-&gt;mat);<br\/> <br\/>    printf(&quot;\\n&quot;);<br\/>}<br\/> <br\/>\/\/ Comparison object to be used to order the heap<br\/>struct comp<br\/>{<br\/>    bool operator()(const Node* lhs, const Node* rhs) const<br\/>    {<br\/>        return (lhs-&gt;cost + lhs-&gt;level) &gt; (rhs-&gt;cost + rhs-&gt;level);<br\/>    }<br\/>};<br\/> <br\/>\/\/ Function to solve N*N - 1 puzzle algorithm using<br\/>\/\/ Branch and Bound. x and y are blank tile coordinates<br\/>\/\/ in initial state<br\/>void solve(int initial[N][N], int x, int y,<br\/>           int final[N][N])<br\/>{<br\/>    \/\/ Create a priority queue to store live nodes of<br\/>    \/\/ search tree;<br\/>    priority_queue&lt;Node*, std::vector&lt;Node*&gt;, comp&gt; pq;<br\/> <br\/>    \/\/ create a root node and calculate its cost<br\/>    Node* root = newNode(initial, x, y, x, y, 0, NULL);<br\/>    root-&gt;cost = calculateCost(initial, final);<br\/> <br\/>    \/\/ Add root to list of live nodes;<br\/>    pq.push(root);<br\/> <br\/>    \/\/ Finds a live node with least cost,<br\/>    \/\/ add its childrens to list of live nodes and<br\/>    \/\/ finally deletes it from the list.<br\/>    while (!pq.empty())<br\/>    {<br\/>        \/\/ Find a live node with least estimated cost<br\/>        Node* min = pq.top();<br\/> <br\/>        \/\/ The found node is deleted from the list of<br\/>        \/\/ live nodes<br\/>        pq.pop();<br\/> <br\/>        \/\/ if min is an answer node<br\/>        if (min-&gt;cost == 0)<br\/>        {<br\/>            \/\/ print the path from root to destination;<br\/>            printPath(min);<br\/>            return;<br\/>        }<br\/> <br\/>        \/\/ do for each child of min<br\/>        \/\/ max 4 children for a node<br\/>        for (int i = 0; i &lt; 4; i++)<br\/>        {<br\/>            if (isSafe(min-&gt;x + row[i], min-&gt;y + col[i]))<br\/>            {<br\/>                \/\/ create a child node and calculate<br\/>                \/\/ its cost<br\/>                Node* child = newNode(min-&gt;mat, min-&gt;x,<br\/>                              min-&gt;y, min-&gt;x + row[i],<br\/>                              min-&gt;y + col[i],<br\/>                              min-&gt;level + 1, min);<br\/>                child-&gt;cost = calculateCost(child-&gt;mat, final);<br\/> <br\/>                \/\/ Add child to list of live nodes<br\/>                pq.push(child);<br\/>            }<br\/>        }<br\/>    }<br\/>}<br\/> <br\/>\/\/ Driver code<br\/>int main()<br\/>{<br\/>    \/\/ Initial configuration<br\/>    \/\/ Value 0 is used for empty space<br\/>    int initial[N][N] =<br\/>    {<br\/>        {1, 2, 3},<br\/>        {5, 6, 0},<br\/>        {7, 8, 4}<br\/>    };<br\/> <br\/>    \/\/ Solvable Final configuration<br\/>    \/\/ Value 0 is used for empty space<br\/>    int final[N][N] =<br\/>    {<br\/>        {1, 2, 3},<br\/>        {5, 8, 6},<br\/>        {0, 7, 4}<br\/>    };<br\/> <br\/>    \/\/ Blank tile coordinates in initial<br\/>    \/\/ configuration<br\/>    int x = 1, y = 2;<br\/> <br\/>    solve(initial, x, y, final);<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>&nbsp;<\/p>\n<p>Output :<\/p>\n<pre>1 2 3 \r\n5 6 0 \r\n7 8 4 \r\n\r\n1 2 3 \r\n5 0 6 \r\n7 8 4 \r\n\r\n1 2 3 \r\n5 8 6 \r\n7 0 4 \r\n\r\n1 2 3 \r\n5 8 6 \r\n0 7 4<\/pre>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Branch and Bound (8 puzzle Problem) &#8211; Branch and Bound &#8211; We have introduced Branch and Bound and discussed 0\/1 Knapsack problem in below posts.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,79474],"tags":[79653,79652,79655,79651,79654,79656,79657,79646,79649,79644,79647,79648,79645,77655,79650],"class_list":["post-26679","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-branch-and-bound","tag-15-puzzle-problem-in-c","tag-15-puzzle-problem-solution","tag-15-puzzle-problem-time-complexity","tag-15-puzzle-problem-using-branch-and-bound","tag-15-puzzle-problem-using-branch-and-bound-ppt","tag-15-puzzle-problem-using-branch-and-bound-program-in-c","tag-15-puzzle-solvability","tag-8-puzzle-problem-game","tag-8-puzzle-problem-in-c-code","tag-8-puzzle-problem-solution-in-ai","tag-8-puzzle-problem-using-breadth-first-search","tag-algorithm-to-solve-15-puzzle-problem","tag-fifo-branch-and-bound","tag-how-to-solve-8-puzzle-problem","tag-least-cost-search-branch-and-bound-ppt"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26679","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26679"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26679\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26679"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26679"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26679"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}