Tuesday, August 9, 2016

Objective : Solve a 8-puzzle program using the A* search algorithm. 


The 8-puzzle problem is some arrangement of numbers 1 to 8 in  a 3 x 3 grid with 8 square blocks labeled 1 to 8 and one blank square. 
The blocks will be arranged so that they are in order. 


The A* algorithm is like this: 
Take a snapshot of the puzzle as it appears initially and put it in the priority queue.  
We keep track of previous snapshot and current snapshot.  
The current snapshot is the one in the priority queue and the previous initially is null. 
We remove the snapshot with the minimum priority and insert into it all the neighbouring snapshots.
A neighbouring snapshot is one with that can be reached in one move. 
The priority for a snapshot is found by counting the number of blocks in the wrong position,  
plus the number of moves made so far to get to the snapshot. 
The minimum number of moves must at least be the priority of a snapshot. 
We repeat the procedure until desired goal snapshot is found. 




The priority or cost of a particular state is described in terms of three parameters
f, g and h
g is the cost it took to get to that square and is the number of snapshots we passed from the start
h is our guess to how much it will take to reach the goal and is counted as the number of squares that are not in their place
f = g + h
A star is also called the best path algorithm
The algorithm is described this way:
var open = new List<8Puzzle>();
var closed = new List<8Puzzle>();
void BestPath(8Puzzle start, 8Puzzle goal, ref List<8Puzzle> open, ref List<8Puzzle> closed)
{
open.add(8Puzzle);
while (open.Count > 0)
{
     var q = open.min();
     open.remove(q);
     var neighbors = getNeighbors(q)
     foreach (var neighbor in neighbors){
             if (neighbor == goal) return;
             neighbor.parent = q
             neighbor.g = q.g + distance(q, neighbor)
             neighbor.h = distance(goal, neighbor)
             neighbor.f = neighbor.g + neighbor.h
             
             var seen = open.First( x == neighbor);
             if (seen != null && seen.f < neighbor.f) continue;
             seen = closed.First(x == neighbor);
             if (seen != null && seen.f < neighbor.f) continue;
             open.add(neighbor)
           }
     closed.Add(q);
}
}

No comments:

Post a Comment