Monsters

You and some monsters are in a labyrinth. When taking a step in some direction in the labyrinth, each monster may simultaneously take one as well. Your goal is to reach one of the boundary squares without ever sharing a square with a monster.

Your task is to find out if your goal is possible, and if it is, print a path that you can follow. Your plan has to work in any situation; even if the monsters know your path beforehand.

Example:

Input: n = 5, m = 8, grid = {"########", "#M..A..#", "#.#.M#.#", "#M#..#...", "#.######"}

Output:

YES 5 RRDDR

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

//all four directions
int dx[] = {-1100};
int dy[] = {001, -1};

//direction up,down,right,left
char dir[] = {'U''D''R''L'};
int dp[1005][1005];

bool isValid(vector<string&gridint nint mint xint y)
{
    if (x < 0 || x >= n || y < 0 || y >= m || grid[x][y] != '.')
        return false;
    return true;
}
void monsters(int nint mvector<string&grid)
{

    queue<pair<intint>> q;
    int xy;
    for (int i = 0i < ni++)
    {
        for (int j = 0j < mj++)
        {
            if (grid[i][j] == 'M')
                q.push({ij});
            else if (grid[i][j] == 'A')
            {
                x = i;
                y = j;
            }
        }
    }
    q.push({xy});
    dp[x][y] = -1;
    while (!q.empty())
    {
        pair<intintp = q.front();
        x = p.first;
        y = p.second;
        q.pop();
        if (grid[x][y] == 'A' && (x == 0 || x == n - 1 ||
 y == 0 || y == m - 1))
        {
            cout << "YES\n";
            string ans;
            int d = dp[x][y];
            while (d != -1)
            {
                ans += dir[d];
                x -= dx[d];
                y -= dy[d];
                d = dp[x][y];
            }
            reverse(ans.begin(), ans.end());
            cout << ans.size() << "\n";
            cout << ans;
            return;
        }
        for (int i = 0i < 4i++)
        {
            int newX = x + dx[i];
            int newY = y + dy[i];
            if (!isValid(gridnmnewXnewY))
                continue;
            else
            {
                grid[newX][newY] = grid[x][y];
                if (grid[newX][newY] == 'A')
                    dp[newX][newY] = i;
                q.push({newXnewY});
            }
        }
    }
    cout << "NO\n";
}
int main()
{
    int n = 5m = 8;

    vector<stringgrid = {"########",
                           "#M..A..#",
                           "#.#.M#.#",
                           "#M#..#...",
                           "#.######"};

    monsters(nmgrid);

    return 0;
}


No comments:

Post a Comment