You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
2.4 KiB

2 years ago
  1. # Auto solver implementation with A-star
  2. The board is represented as a 1D array initially, which is converted to a 2D matrix(list of list of int).
  3. Lets understand the implementation with a 3 * 3 slide puzzle. However, this will work for any nXn slide puzzle.
  4. ```
  5. [1 2 3 4 5 6 7 8 ]
  6. Let's use the A star algorithm to solve the 8 puzzle problem.
  7. Let the initial state be
  8. []
  9. Let the goal state be
  10. []
  11. The search tree for the initial state will look like this
  12. At each step, we move our empty block either left or down. We need to make sure we do not reach the original state through these moves, as they can lead to infinite loops.
  13. There are two entities we need to keep into mind
  14. G is the number of steps required to reach the goal state from the initial state. Estimated number of steps from current state to goal state.
  15. H is Manhattan distance. It is the estimated distance to goal.
  16. It can be calculated by adding the difference in the row and column for all the blocks of the initial state from the goal state.
  17. Identify the path with the minimum g+h.
  18. These are the variables in `puzzle_solver.dart` :
  19. * queue - Priority queue
  20. * visited - set
  21. * goal_states - list
  22. * root - object of Node class
  23. * board: board
  24. * previous: null,
  25. * heuristic: manhattan(board, goalStates[currGoal])
  26. * depth: int
  27. >Each node can have maximum of 4 children, the graph fill further expand in a similar fashion with each child pointing to the parent using pointer.
  28. >The g score here, which is the cost of the move will increase by 1 at each depth since each tile sliding to the blank space represents one move and in the end we need to get the optimal moves for the puzzle instance, this basically mean that we have to add 1 to the g score of the parent before storing it in the child nodes.
  29. >Heuristics returns the number of tiles that are not in their final position
  30. >Manhattan Distance of a tile is the distance or the number of slides/tiles away it is from it’s goal state.Thus, for a certain state the Manhattan distance will be the sum of the Manhattan distances of all the tiles except the blank tile.
  31. Functions :
  32. * rowColGoalStates() - Returns the goal states for the slide puzzle
  33. queue is initialised with the first node object, the initial board configuration.
  34. We loop till the queue isnt empty.
  35. Inside the loop, we pop an element from the top.
  36. If it possible to reach the goal state from that configuration