Problem Statement

There is a rectangle with left bottom as  (0, 0) and right up as (x, y). There are N circles such that their centers are inside the rectangle.Radius of each circle is R. Now we need to find out if it is possible that we can move from (0, 0) to (x, y) without touching any circle.

Note : We can move from any cell to any of its 8 adjecent neighbours and we cannot move outside the boundary of the rectangle at any point of time.Input Format

1st argument given is an Integer x. 2nd argument given is an Integer y. 3rd argument given is an Integer N, number of circles. 4th argument given is an Integer R, radius of each circle. 5th argument given is an Array A of size N, where A[i] = x cordinate of ith circle 6th argument given is an Array B of size N, where B[i] = y cordinate of ith circle

Output Format

Return YES or NO depending on weather it is possible to reach cell (x,y) or not starting from (0,0).

Constraints

0 <= x, y, R <= 100 1 <= N <= 1000 Center of each circle would lie within the grid

For Example

`Input: x = 2 y = 3 N = 1 R = 1 A = [2] B = [3] Output: NO

Explanation: There is NO valid path in this case`

Problem Link

Valid Path - InterviewBit

Reference Link

Path in a Rectangle with Circles - GeeksforGeeks

Code (Using BFS)

string Solution::solve(int A, int B, int C, int D, vector<int> &E, vector<int> &F) {
    int m = A;
    int n = B;
    vector<vector<int>> adj(m+1,vector<int>(n+1,1));
    int N =C;
    int r = D;
    
    
    for(int i=0;i<=m;i++)
    {
        for(int j=0;j<=n;j++)
        {
            
            for(int k=0;k<N;k++)
            {
                int dist = (pow(E[k]-i,2)+pow(F[k]-j,2));
                if(dist<=r*r)
                adj[i][j] = 0;
            }
        }
    }
    if(!adj[0][0] || !adj[m][n])
    return "NO";
    vector<int> mx{1,1,1,0,0,-1,-1,-1};
    vector<int> my{-1,0,1,-1,1,-1,0,1};
    queue<pair<int,int>> q;
    q.push({0,0});
    adj[0][0] = 0;
    while(!q.empty())
    {
        auto p = q.front();
        q.pop();
        int i = p.first;
        int j = p.second;
        if(i==m && j==n)
        return "YES";
        
        for(int k=0;k<8;k++)
        {
            int in = i+mx[k];
            int jn = j+my[k];
            
            if(in<0 || jn<0 ||in>m||jn>n||adj[in][jn]==0)
            continue;
            
            q.push({in,jn});
            adj[in][jn] = 0;
            
        }
    }
    return "NO";
}