Search code examples
c++algorithmrecursionpath-finding

C++ 9x9 cell board ball movement path checking


There have a 9x9 cell board (2d-array) with different color balls. Player can move a ball from one cell to another cell. The ball can move with a path which is no ball on the cell between the current cell and destination cell.

I only think I have to use recurrence in implement this path checking. But I don't know how to achieve this function.

I had try to implement the function. But I know it will cause infinitely loop.

bool board::moveCheck(int x1, int y1, int x2, int y2)
{
    if(x1==x2&&y1==y2)
        return true;
    else if(y1-1>=0)
        board::moveCheck(x1,y1-1,x2,y2);
    else if(y1+1<9)
        board::moveCheck(x1,y1+1,x2,y2);
    else if(x1-1>=0)
        board::moveCheck(x1-1,y1+1,x2,y2);
    else if(x1+1<9)
        board::moveCheck(x1+1,y1+1,x2,y2);
    else
        return false;
}

Solution

  • Your code has many problems with it, and it's hard to see how it can be fixed without a total rewrite. Here are a few pointers:

    1. When you recursively call the function, you need to do something with the return value. At the moment you're throwing it away.

    2. Your code has undefined behaviour because it does not always return a value. Consider the case where y1 - 1 >= 0. You will call moveCheck(), throw away the return value (assuming it even returns at all), and then exit the conditional block, at which point the function ends, without returning anything.

    3. You have a member function that does not seem to inspect any member variables. Where are you checking to see if there are obstacles in the path?

    4. It's not entirely clear what x1, y1, x2, and y2 are. Either give them self documenting names, or provide documenting comments. I'm guessing that they're the source and destination coordinates, but it's not clear why you're comparing them against each other, if it's the presence of balls in the path that you're interested in.