Advertisement
ramprakash110109

8NumberPuzzleWithExplanation

Jun 4th, 2022
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.84 KB | None | 0 0
  1. package puzzle;
  2.  
  3.  
  4. //Java Program to print path from root node to destination node
  5. //for N*N -1 puzzle algorithm using Branch and Bound
  6. //The solution assumes that instance of puzzle is solvable
  7. import java.io.*;
  8. import java.util.*;
  9.  
  10. public class Puzzle
  11. {
  12. public static int N = 3;
  13. public static class Node
  14. {
  15.  
  16. // stores the parent node of the current node
  17. // helps in tracing path when the answer is found
  18. Node parent;
  19. int mat[][] = new int[N][N];// stores matrix
  20. int x, y;// stores blank tile coordinates
  21. int cost;// stores the number of misplaced tiles
  22. int level;// stores the number of moves so far
  23. }
  24.  
  25. // Function to print N x N matrix
  26. public static void printMatrix(int mat[][]){
  27. for(int i = 0; i < N; i++){
  28. for(int j = 0; j < N; j++){
  29. System.out.print(mat[i][j]+" ");
  30. }
  31. System.out.println("");
  32. }
  33. }
  34.  
  35. // Function to allocate a new node
  36. public static Node newNode(int mat[][], int x, int y,
  37. int newX, int newY, int level,
  38. Node parent){
  39. Node node = new Node();
  40. node.parent = parent;// set pointer for path to root
  41.  
  42. // copy data from parent node to current node
  43. node.mat = new int[N][N];
  44. for(int i = 0; i < N; i++){
  45. for(int j = 0; j < N; j++){
  46. node.mat[i][j] = mat[i][j];
  47. }
  48. }
  49.  
  50. // move tile by 1 position
  51. int temp = node.mat[x][y];
  52. node.mat[x][y] = node.mat[newX][newY];
  53. node.mat[newX][newY]=temp;
  54.  
  55. node.cost = Integer.MAX_VALUE;// set number of misplaced tiles
  56. node.level = level;// set number of moves so far
  57.  
  58. // update new blank tile coordinates
  59. node.x = newX;
  60. node.y = newY;
  61.  
  62. return node;
  63. }
  64.  
  65. // bottom, left, top, right
  66. public static int row[] = { 1, 0, -1, 0 };
  67. public static int col[] = { 0, -1, 0, 1 };
  68.  
  69. // Function to calculate the number of misplaced tiles
  70. // ie. number of non-blank tiles not in their goal position
  71. public static int calculateCost(int initialMat[][], int finalMat[][])
  72. {
  73. int count = 0;
  74. for (int i = 0; i < N; i++)
  75. for (int j = 0; j < N; j++)
  76. if (initialMat[i][j]!=0 && initialMat[i][j] != finalMat[i][j])
  77. count++;
  78. return count;
  79. }
  80.  
  81. // Function to check if (x, y) is a valid matrix coordinate
  82. public static int isSafe(int x, int y)
  83. {
  84. return (x >= 0 && x < N && y >= 0 && y < N)?1:0;
  85. }
  86.  
  87. // print path from root node to destination node
  88. public static void printPath(Node root){
  89. if(root == null){
  90. return;
  91. }
  92. printPath(root.parent);
  93. printMatrix(root.mat);
  94. System.out.println("");
  95. }
  96.  
  97. // Comparison object to be used to order the heap
  98. public static class comp implements Comparator<Node>{
  99. @Override
  100. public int compare(Node lhs, Node rhs){
  101. return (lhs.cost + lhs.level) > (rhs.cost+rhs.level)?1:-1;
  102. }
  103. }
  104.  
  105. // Function to solve N*N - 1 puzzle algorithm using
  106. // Branch and Bound. x and y are blank tile coordinates
  107. // in initial state
  108. public static void solve(int initialMat[][], int x,
  109. int y, int finalMat[][])
  110. {
  111.  
  112. // Create a priority queue to store live nodes of search tree
  113. PriorityQueue<Node> pq = new PriorityQueue<>(new comp());
  114.  
  115. // create a root node and calculate its cost
  116. Node root = newNode(initialMat, x, y, x, y, 0, null);
  117. root.cost = calculateCost(initialMat,finalMat);
  118.  
  119. // Add root to list of live nodes;
  120. pq.add(root);
  121.  
  122. // Finds a live node with least cost,
  123. // add its childrens to list of live nodes and
  124. // finally deletes it from the list.
  125. while(!pq.isEmpty())
  126. {
  127. Node min = pq.peek();// Find a live node with least estimated cost
  128. pq.poll();// The found node is deleted from the list of live nodes
  129.  
  130. // if min is an answer node
  131. if(min.cost == 0){
  132. printPath(min);// print the path from root to destination;
  133. return;
  134. }
  135. // do for each child of min
  136. // max 4 children for a node
  137. for (int i = 0; i < 4; i++)
  138. {
  139. if (isSafe(min.x + row[i], min.y + col[i])>0)
  140. {
  141. // create a child node and calculate
  142. // its cost
  143. Node child = newNode(min.mat, min.x, min.y, min.x + row[i],min.y + col[i], min.level + 1, min);
  144. child.cost = calculateCost(child.mat, finalMat);
  145.  
  146. // Add child to list of live nodes
  147. pq.add(child);
  148. }
  149. }
  150. }
  151. }
  152. public static void main(String[] args) {
  153. // TODO Auto-generated method stub
  154. try {
  155. // Initial configuration
  156. // Value 0 is used for empty space
  157. int initialMat[][] =
  158. {
  159. {1, 2, 3},
  160. {5, 6, 0},
  161. {7, 8, 4}
  162. };
  163.  
  164. // Solvable Final configuration
  165. // Value 0 is used for empty space
  166. int finalMat[][] =
  167. {
  168. {1, 2, 3},
  169. {5, 8, 6},
  170. {0, 7, 4}
  171. };
  172.  
  173. // Blank tile coordinates in initial
  174. // configuration
  175. int x = 1, y = 2;
  176.  
  177. solve(initialMat, x, y, finalMat);
  178.  
  179. }catch(Exception e){
  180. System.out.println("Exception is "+e);
  181. }
  182. }
  183.  
  184. }
  185.  
  186. //This code is contributed by shruti456rawal
  187.  
  188.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement