1

if i have a maze my code should see if i can walk on every free space (represented by dot '.') or not so i tried backtracking. the player can move in the four main directions but he can't choose the number of steps (he walks until he collides with something) and start to move again from this point. for simplicity i made only the down movement and tried to give it a test case to see if it's working or not. the code should return 1 from the backtracking but it's returning 0 for some reason so i need some help.

this is the link of the code on ideone if more details needed: https://ideone.com/AbeS0n

this is the basic code functions:

bool canMove(int x, int y)
{
    return (grid[x + 1][y] == '.' && x + 1 < n + 1)
        || (grid[x - 1][y] == '.' && x - 1 > 0)
        || (grid[x][y + 1] == '.' && y + 1 < n + 1)
        || (grid[x][y - 1] == '.' && y - 1 > 0);
}

vector<string> ans;
bool valid(int x, int y)
{
    return x > 0 && x < n + 1 && y > 0 && y < n + 1 && grid[x][y] == '.';
}
bool solve(int x, int y)
{
    //basecase
    if(sol) return 1;
    if(!canMove(x, y))
    {
        for(int i = 1 ; i <= n; ++i)
            for(int j = 1; j <= n; ++j)
                if(grid[i][j] == '.')
                    return 0;
        sol = 1;            
        return 1;
    }
    if(valid(x + 1, y))
    {
        int end = n;
        //Do
        for(int i = x + 1; i <= end; ++i)
        {
            if(valid(i, y))
            {
                grid[i][y] = 'x';
            }
            else
            {
                end = i;
                break;
            }
        }
        ans.push_back("Down");
        
        //Recurse
        solve(end, y);
        
        //Undo
        for(int i = end; i > x; --i)
            grid[i][y] = '.';
        ans.pop_back();
    }
    return 0;
}

0 Answers0