Grid

You are given a grid A of size N×M, two integers (SiSj), and Q tasks. Each task contains two integers, (DiDj). Each cell in the grid is either empty cells denoted by O (Capital English character 'o') or occupied cells denoted by ∗. Initially, you are at (SiSj). Find the minimum number of steps that you have to take to reach (DiDj) from (SiSj) without traversing the occupied cells.

In a single step, you can move from any cell (i,j) to the 4 neighboring cells i.e. (i1,j), (i+1,j), (i,j1) and (i,j+1) provided these cells are inside grid A.

Example:

Input:  n = 3, m = 3, grid={"O*O","OOO","*OO"}, srcx = 2, srcy = 2, a = 1, b = 1
Output: 2

Approach

C++

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

int nm;
char grid[1001][1001];
int dx[] = {-1010};
int dy[] = {010, -1};
int vis[1001][1001];
int dist[1001][1001];

bool isValid(int xint y)
{
    if (x < 1 || x > n || y < 1 || y > m)
        return false;
    if (vis[x][y] == 1 || grid[x][y] == '*')
        return false;
    return true;
}

void bfs(int srcxint srcy)
{
    queue<pair<intint>> q;
    vis[srcx][srcy] = 1;

    q.push({srcxsrcy});
    dist[srcx][srcy] = 0;
    while (!q.empty())
    {
        int currx = q.front().first;
        int curry = q.front().second;
        q.pop();
        for (int i = 0i < 4i++)
        {
            if (isValid(currx + dx[i], curry + dy[i]))
            {
                int newx = currx + dx[i];
                int newy = curry + dy[i];
                q.push({newxnewy});
                dist[newx][newy] = dist[currx][curry] + 1;
                vis[newx][newy] = 1;
            }
        }
    }
}
int main()
{

    n = 3;
    m = 3;

    vector<stringvec = {"O*O""OOO""*OO"};
    for (int i = 1i <= ni++)
    {
        for (int j = 1j <= mj++)
            grid[i][j] = vec[i - 1][j - 1];
    }

    int srcx = 2srcy = 2;

    bfs(srcxsrcy);

    int a = 1b = 1;
    if (a == srcx && b == srcy)
        cout << 0 << "\n";
    else if (dist[a][b] == 0)
        cout << -1 << "\n";
    else
        cout << dist[a][b<< "\n";

    return 0;
}


No comments:

Post a Comment