{"id":25580,"date":"2017-10-15T19:25:16","date_gmt":"2017-10-15T13:55:16","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25580"},"modified":"2017-10-15T19:25:16","modified_gmt":"2017-10-15T13:55:16","slug":"backtracking-set-2-rat-maze-2-2","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/backtracking-set-2-rat-maze-2-2\/","title":{"rendered":"JAVA Programming-Backtracking Set 2 (Rat in a Maze)"},"content":{"rendered":"<p>We have discussed Backtracking and Knight\u2019s tour problem in <a href=\"http:\/\/www.geeksforgeeks.org\/?p=12916\" target=\"_blank\" rel=\"noopener\">Set 1<\/a>. Let us discuss Rat in a <a href=\"http:\/\/en.wikipedia.org\/wiki\/Maze\" target=\"_blank\" rel=\"noopener\">Maze <\/a>as another example problem that can be solved using Backtracking.<span id=\"more-13376\"><\/span><\/p>\n<p>A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination. The rat can move only in two directions: forward and down.<br \/>\nIn the maze matrix, 0 means the block is dead end and 1 means the block can be used in the path from source to destination. Note that this is a simple version of the typical Maze problem. For example, a more complex version can be that the rat can move in 4 directions and a more complex version can be with limited number of moves.<\/p>\n<p>Following is an example maze.<\/p>\n<pre>Gray blocks are dead ends (value = 0).<\/pre>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-25576\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Doooood.png\" alt=\"Rat in a Maze\" width=\"300\" height=\"260\" \/><\/p>\n<p>Following is binary matrix representation of the above maze.<\/p>\n<pre>                {1, 0, 0, 0}\r\n                {1, 1, 0, 1}\r\n                {0, 1, 0, 0}\r\n                {1, 1, 1, 1}<\/pre>\n<p>Following is maze with highlighted solution path.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-25577\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Doooood11.png\" alt=\"Rat in a Maze\" width=\"300\" height=\"267\" \/><\/p>\n<p>Following is the solution matrix (output of program) for the above input matrx.<\/p>\n<pre>                {1, 0, 0, 0}\r\n                {1, 1, 0, 0}\r\n                {0, 1, 0, 0}\r\n                {0, 1, 1, 1}\r\n All enteries in solution path are marked as 1.<\/pre>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Naive Algorithm<\/strong><br \/>\nThe Naive Algorithm is to generate all paths from source to destination and one by one check if the generated path satisfies the constraints.<\/p>\n<pre>while there are untried paths\r\n{\r\n   generate the next path\r\n   if this path has all blocks as 1\r\n   {\r\n      print this path;\r\n   }\r\n}<\/pre>\n<p><strong>Backtrackng Algorithm<\/strong><\/p>\n<pre>If destination is reached\r\n    print the solution matrix\r\nElse\r\n   a) Mark current cell in solution matrix as 1. \r\n   b) Move forward in horizontal direction and recursively check if this \r\n       move leads to a solution. \r\n   c) If the move chosen in the above step doesn't lead to a solution\r\n       then move down and check if  this move leads to a solution. \r\n   d) If none of the above solutions work then unmark this cell as 0 \r\n       (BACKTRACK) and return false.\r\n<\/pre>\n<p><strong>Implementation of Backtracking solution<\/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 to solve Rat in a Maze problem using<br\/>   backtracking *\/<br\/> <br\/>public class RatMaze<br\/>{<br\/>    final int N = 4;<br\/> <br\/>    \/* A utility function to print solution matrix<br\/>       sol[N][N] *\/<br\/>    void printSolution(int sol[][])<br\/>    {<br\/>        for (int i = 0; i &lt; N; i++)<br\/>        {<br\/>            for (int j = 0; j &lt; N; j++)<br\/>                System.out.print(&quot; &quot; + sol[i][j] +<br\/>                                 &quot; &quot;);<br\/>            System.out.println();<br\/>        }<br\/>    }<br\/> <br\/>    \/* A utility function to check if x,y is valid<br\/>        index for N*N maze *\/<br\/>    boolean isSafe(int maze[][], int x, int y)<br\/>    {<br\/>        \/\/ if (x,y outside maze) return false<br\/>        return (x &gt;= 0 &amp;&amp; x &lt; N &amp;&amp; y &gt;= 0 &amp;&amp;<br\/>                y &lt; N &amp;&amp; maze[x][y] == 1);<br\/>    }<br\/> <br\/>    \/* This function solves the Maze problem using<br\/>       Backtracking. It mainly uses solveMazeUtil()<br\/>       to solve the problem. It returns false if no<br\/>       path is possible, otherwise return true and<br\/>       prints the path in the form of 1s. Please note<br\/>       that there may be more than one solutions, this<br\/>       function prints one of the feasible solutions.*\/<br\/>    boolean solveMaze(int maze[][])<br\/>    {<br\/>        int sol[][] = {{0, 0, 0, 0},<br\/>            {0, 0, 0, 0},<br\/>            {0, 0, 0, 0},<br\/>            {0, 0, 0, 0}<br\/>        };<br\/> <br\/>        if (solveMazeUtil(maze, 0, 0, sol) == false)<br\/>        {<br\/>            System.out.print(&quot;Solution doesn&#039;t exist&quot;);<br\/>            return false;<br\/>        }<br\/> <br\/>        printSolution(sol);<br\/>        return true;<br\/>    }<br\/> <br\/>    \/* A recursive utility function to solve Maze<br\/>       problem *\/<br\/>    boolean solveMazeUtil(int maze[][], int x, int y,<br\/>                          int sol[][])<br\/>    {<br\/>        \/\/ if (x,y is goal) return true<br\/>        if (x == N - 1 &amp;&amp; y == N - 1)<br\/>        {<br\/>            sol[x][y] = 1;<br\/>            return true;<br\/>        }<br\/> <br\/>        \/\/ Check if maze[x][y] is valid<br\/>        if (isSafe(maze, x, y) == true)<br\/>        {<br\/>            \/\/ mark x,y as part of solution path<br\/>            sol[x][y] = 1;<br\/> <br\/>            \/* Move forward in x direction *\/<br\/>            if (solveMazeUtil(maze, x + 1, y, sol))<br\/>                return true;<br\/> <br\/>            \/* If moving in x direction doesn&#039;t give<br\/>               solution then  Move down in y direction *\/<br\/>            if (solveMazeUtil(maze, x, y + 1, sol))<br\/>                return true;<br\/> <br\/>            \/* If none of the above movements work then<br\/>               BACKTRACK: unmark x,y as part of solution<br\/>               path *\/<br\/>            sol[x][y] = 0;<br\/>            return false;<br\/>        }<br\/> <br\/>        return false;<br\/>    }<br\/> <br\/>    public static void main(String args[])<br\/>    {<br\/>        RatMaze rat = new RatMaze();<br\/>        int maze[][] = {{1, 0, 0, 0},<br\/>            {1, 1, 0, 1},<br\/>            {0, 1, 0, 0},<br\/>            {1, 1, 1, 1}<br\/>        };<br\/>        rat.solveMaze(maze);<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p>Output: The 1 values show the path for rat<\/p>\n<pre> 1  0  0  0 \r\n 1  1  0  0 \r\n 0  1  0  0 \r\n 0  1  1  1<\/pre>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>JAVA Programming-Backtracking Set 2 (Rat in a Maze) &#8211; Backtracking &#8211; A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. <\/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,74160,74164,73915,74162,74154,74163,74146,74166],"class_list":["post-25580","post","type-post","status-publish","format-standard","hentry","category-backtracking-algorithm","category-coding","category-java","tag-backtracking-algorithm","tag-backtracking-algorithm-example","tag-backtracking-algorithm-pdf","tag-backtracking-algorithm-tutorial","tag-backtracking-problems","tag-dynamic-programming-geeksforgeeks","tag-graph-coloring-using-backtracking","tag-maze-solving-algorithm","tag-reverse-a-doubly-linked-list"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25580","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=25580"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25580\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25580"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25580"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25580"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}