Search code examples
algorithmtiles-game

Path with least turns in rectangular grid algorithm


I am stuck for last 4 days in an algorithm. I am working on Mahjong Safari type game (http://www.pogo.com/games/mahjongsafari), and I want to develop path between two tiles with least number of tiles.

I already applied A* algorithm with Manhattan Hueristic, but that generates shortest path with lots of turns. There is no need of shortest path, I just need path with min turns (preferably 2). Below is image from Mahjong Safari game, which generates path between 2 tiles. You will notice that the path from A to B and path from B to A are different.

enter image description here

Please help me, in any code or any algorithm name or any logic you think could work.

EDIT: The Solution I applied for this:

I used genuine A* Algorithm first to find shortest path, and I used Manhattan distance as heuristic goal estimate. To straighten the path more, and choose path with least number of turns, i used following tactic in each iteration:

Tile first = currentNode.parent;
Tile curr  = currentNode;
Tile last  = successorOfCurrentNode;
if (first != null)
{
    if ((first.X == curr.X && first.Y != curr.Y) && (curr.Y == last.Y && curr.X != last.X))
    {
        // We got turn
    currentNode.Cost += 10;
    currentNode.calcuateTotalCost();

        successorOfCurrentNode.Cost += 5;
    successorOfCurrentNode.calcuateTotalCost();
    }
    else if ((first.X != curr.X && first.Y == curr.Y) && (curr.X == last.X && curr.Y != last.Y))
    {
        // We got turn
    currentNode.Cost += 10;
    currentNode.calcuateTotalCost();

        successorOfCurrentNode.Cost += 5;
    successorOfCurrentNode.calcuateTotalCost();
    }

}


Solution

  • The Solution I applied for this:

    I used genuine A* Algorithm first to find shortest path, and I used Manhattan distance as heuristic goal estimate. To straighten the path more, and choose path with least number of turns, i used following tactic in each iteration:

    enter code here
    
    Tile first = currentNode.parent;
    Tile curr  = currentNode;
    Tile last  = successorOfCurrentNode;
    if (first != null)
    {
        if ((first.X == curr.X && first.Y != curr.Y) && (curr.Y == last.Y && curr.X != last.X))
        {
            // We got turn
            currentNode.Cost += 10;
            currentNode.calcuateTotalCost();
    
            successorOfCurrentNode.Cost += 5;
            successorOfCurrentNode.calcuateTotalCost();
        }
        else if ((first.X != curr.X && first.Y == curr.Y) && (curr.X == last.X && curr.Y != last.Y))
        {
            // We got turn
            currentNode.Cost += 10;
            currentNode.calcuateTotalCost();
    
            successorOfCurrentNode.Cost += 5;
            successorOfCurrentNode.calcuateTotalCost();
        }
    
    }