{"id":25533,"date":"2017-10-15T19:10:46","date_gmt":"2017-10-15T13:40:46","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25533"},"modified":"2017-10-15T19:10:46","modified_gmt":"2017-10-15T13:40:46","slug":"backtracking-set-1-knights-tour-problem-2","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/backtracking-set-1-knights-tour-problem-2\/","title":{"rendered":"JAVA Programming-Backtracking Set 1 (The Knight\u2019s tour problem)"},"content":{"rendered":"<p>Backtracking is an algorithmic paradigm that tries different solutions until finds a solution that \u201cworks\u201d. Problems which are typically solved using backtracking technique have following property in common. These problems can only be solved by trying every possible configuration and each configuration is tried only once. A Naive solution for these problems is to try all configurations and output a configuration that follows given problem constraints. Backtracking works in incremental way and is an optimization over the Naive solution where all possible configurations are generated and tried.<\/p>\n<p>For example, consider the following Knight\u2019s Tour problem.<br \/>\nThe knight is placed on the first block of an empty board and, moving according to the rules of chess, must visit each square exactly once.<\/p>\n<p align=\"center\"><strong>Path followed by Knight to cover all the cells<\/strong><\/p>\n<p>Following is chessboard with 8 x 8 cells. Numbers in cells indicate move number of Knight.<br \/>\n<img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-140229\" src=\"http:\/\/www.geeksforgeeks.org\/wp-content\/uploads\/knight-tour-problem1.png\" alt=\"knight-tour-problem\" width=\"668\" height=\"224\" \/><br \/>\nLet us first discuss the Naive algorithm for this problem and then the Backtracking algorithm.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Naive Algorithm for Knight\u2019s tour<\/strong><br \/>\nThe Naive Algorithm is to generate all tours one by one and check if the generated tour satisfies the constraints.<\/p>\n<pre>while there are untried tours\r\n{ \r\n   generate the next tour \r\n   if this tour covers all squares \r\n   { \r\n      print this path;\r\n   }\r\n}<\/pre>\n<p>Backtracking works in an incremental way to attack problems. Typically, we start from an empty solution vector and one by one add items (Meaning of item varies from problem to problem. In context of Knight\u2019s tour problem, an item is a Knight\u2019s move). When we add an item, we check if adding the current item violates the problem constraint, if it does then we remove the item and try other alternatives. If none of the alternatives work out then we go to previous stage and remove the item added in the previous stage. If we reach the initial stage back then we say that no solution exists. If adding an item doesn\u2019t violate constraints then we recursively add items one by one. If the solution vector becomes complete then we print the solution.<\/p>\n<p>Backtracking Algorithm for Knight\u2019s tour<br \/>\nFollowing is the Backtracking algorithm for Knight\u2019s tour problem.<\/p>\n<p>If all squares are visited<br \/>\nprint the solution<br \/>\nElse<\/p>\n<ul>\n<li>\u00a0Add one of the next moves to solution vector and recursively<br \/>\ncheck if this move leads to a solution. (A Knight can make maximum<br \/>\neight moves. We choose one of the 8 moves in this step).<\/li>\n<li>If the move chosen in the above step doesn&#8217;t lead to a solution<br \/>\nthen remove this move from the solution vector and try other<br \/>\nalternative moves.<\/li>\n<li>\u00a0If none of the alternatives work then return false (Returning false<br \/>\nwill remove the previously added item in recursion and if false is<br \/>\nreturned by the initial call of recursion then &#8220;no solution exists&#8221; )<\/li>\n<\/ul>\n<p>Following are implementations for Knight\u2019s tour problem. It prints one of the possible solutions in 2D matrix form. Basically, the output is a 2D 8*8 matrix with numbers from 0 to 63 and these numbers show steps made by Knight.<\/p>\n[ad type=&#8221;banner&#8221;]\n<strong>JAVA\u00a0Progrmming<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">JAVA<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Java program for Knight Tour problem<br\/>class KnightTour {<br\/>    static int N = 8;<br\/> <br\/>    \/* A utility function to check if i,j are<br\/>       valid indexes for N*N chessboard *\/<br\/>    static boolean isSafe(int x, int y, int sol[][]) {<br\/>        return (x &gt;= 0 &amp;&amp; x &lt; N &amp;&amp; y &gt;= 0 &amp;&amp;<br\/>                y &lt; N &amp;&amp; sol[x][y] == -1);<br\/>    }<br\/> <br\/>    \/* A utility function to print solution<br\/>       matrix sol[N][N] *\/<br\/>    static void printSolution(int sol[][]) {<br\/>        for (int x = 0; x &lt; N; x++) {<br\/>            for (int y = 0; y &lt; N; y++)<br\/>                System.out.print(sol[x][y] + &quot; &quot;);<br\/>            System.out.println();<br\/>        }<br\/>    }<br\/> <br\/>    \/* This function solves the Knight Tour problem<br\/>       using Backtracking.  This  function mainly<br\/>       uses solveKTUtil() to solve the problem. It<br\/>       returns false if no complete tour is possible,<br\/>       otherwise return true and prints the tour.<br\/>       Please note that there may be more than one<br\/>       solutions, this function prints one of the<br\/>       feasible solutions.  *\/<br\/>    static boolean solveKT() {<br\/>        int sol[][] = new int[8][8];<br\/> <br\/>        \/* Initialization of solution matrix *\/<br\/>        for (int x = 0; x &lt; N; x++)<br\/>            for (int y = 0; y &lt; N; y++)<br\/>                sol[x][y] = -1;<br\/> <br\/>       \/* xMove[] and yMove[] define next move of Knight.<br\/>          xMove[] is for next value of x coordinate<br\/>          yMove[] is for next value of y coordinate *\/<br\/>        int xMove[] = {2, 1, -1, -2, -2, -1, 1, 2};<br\/>        int yMove[] = {1, 2, 2, 1, -1, -2, -2, -1};<br\/> <br\/>        \/\/ Since the Knight is initially at the first block<br\/>        sol[0][0] = 0;<br\/> <br\/>        \/* Start from 0,0 and explore all tours using<br\/>           solveKTUtil() *\/<br\/>        if (!solveKTUtil(0, 0, 1, sol, xMove, yMove)) {<br\/>            System.out.println(&quot;Solution does not exist&quot;);<br\/>            return false;<br\/>        } else<br\/>            printSolution(sol);<br\/> <br\/>        return true;<br\/>    }<br\/> <br\/>    \/* A recursive utility function to solve Knight<br\/>       Tour problem *\/<br\/>    static boolean solveKTUtil(int x, int y, int movei,<br\/>                               int sol[][], int xMove[],<br\/>                               int yMove[]) {<br\/>        int k, next_x, next_y;<br\/>        if (movei == N * N)<br\/>            return true;<br\/> <br\/>        \/* Try all next moves from the current coordinate<br\/>            x, y *\/<br\/>        for (k = 0; k &lt; 8; k++) {<br\/>            next_x = x + xMove[k];<br\/>            next_y = y + yMove[k];<br\/>            if (isSafe(next_x, next_y, sol)) {<br\/>                sol[next_x][next_y] = movei;<br\/>                if (solveKTUtil(next_x, next_y, movei + 1,<br\/>                                sol, xMove, yMove))<br\/>                    return true;<br\/>                else<br\/>                    sol[next_x][next_y] = -1;\/\/ backtracking<br\/>            }<br\/>        }<br\/> <br\/>        return false;<br\/>    }<br\/> <br\/>    \/* Driver program to test above functions *\/<br\/>    public static void main(String args[]) {<br\/>        solveKT();<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output<\/strong>:<\/p>\n<pre>  0  59  38  33  30  17   8  63\r\n 37  34  31  60   9  62  29  16\r\n 58   1  36  39  32  27  18   7\r\n 35  48  41  26  61  10  15  28\r\n 42  57   2  49  40  23   6  19\r\n 47  50  45  54  25  20  11  14\r\n 56  43  52   3  22  13  24   5\r\n 51  46  55  44  53   4  21  12\r\n<\/pre>\n<p>Note that Backtracking is not the best solution for the Knight\u2019s tour problem. See below article for other better solutions. The purpose of this post is to explain Backtracking with an example.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>JAVA Programming-Backtracking Set 1 (The Knight\u2019s tour problem) &#8211; Backtracking &#8211; Backtracking is an algorithmic paradigm that tries different solutions until finds a solution that \u201cworks\u201d. Problems which are typically solved using backtracking technique have following property in common. <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[73907,1,2139],"tags":[73908,73915,73912,73940,73947,73914,73944,73941,73929,73926,70705,73938,73942,73930,73916,73919,73911,73933,73945,73939,73932,73923,73924,73918,73922,73925,73910,73946],"class_list":["post-25533","post","type-post","status-publish","format-standard","hentry","category-backtracking-algorithm","category-coding","category-java","tag-backtracking-algorithm","tag-backtracking-algorithm-tutorial","tag-c-programming-problems","tag-chess-algorithm","tag-chess-board-coordinates","tag-chess-board-numbers","tag-chess-board-placement","tag-chess-knight-moves","tag-define-knight","tag-hamiltonian-circuit","tag-hamiltonian-cycle-algorithm","tag-horse-in-chess","tag-how-does-a-knight-move-in-chess","tag-java-knights-tour","tag-java-problems","tag-java-programming-backtracking-set-1-the-knights-tour-problem","tag-knight-and-day","tag-knight-mover","tag-knight-moves-in-chess","tag-knight-tour-problem-solution","tag-knights-journey","tag-knights-tour-algorithm-java","tag-knights-tour-solution","tag-life-a-users-manual","tag-the-knights-tour","tag-what-is-a-knight","tag-what-is-backtracking","tag-what-is-recursion-in-java"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25533","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=25533"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25533\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25533"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25533"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25533"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}