Geek's Village and Well
Geek's village is represented by a 2-D matrix of characters of size n*m, where H - Represents a house W - Represents a well .- Represents open ground N - Prohibited area (Not allowed to enter in this area) Every house in the village needs to take the water from the well, as the family members are so busy with their work, so every family wants to take the water from the well in minimum time, which is possible only if they have to cover as less distance as possible. Your task is to determine the minimum distance that a person in the house should travel to take out the water and carry it back to the house.
A person is allowed to move only in four directions left, right, up, and down. That means if he/she is the cell (ij), then the possible cells he/she can reach in one move are (i,j-1), (i,j+1),(i-1.j),(i+1,j), and the person is not allowed to move out of the grid.
Note: For all the cells containing 'N', 'W', and '.' our answer should be 0, and for all the houses where there is no possibility of taking water our answer should be -1.
SOLUTION:
//User function Template for Java
class Pair{
int first, second;
Pair(int f, int s){
this.first = f;
this.second = s;
}
}
class Solution
{
public int[][] chefAndWells(int n,int m,char grid[][])
{
int[][] ans = new int[n][m];
Queue<Pair> q = new LinkedList<>();
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(grid[i][j] == 'W'){
ans[i][j] = 0;
q.add(new Pair(i, j));
}
else{
ans[i][j] = n*m+1;
}
}
}
int[] drow = {-1, 0, 1, 0};
int[] dcol = {0, 1, 0, -1};
while(!q.isEmpty()){
Pair p = q.poll();
int row = p.first;
int col = p.second;
for(int i = 0; i < 4; i++){
int nrow = row + drow[i];
int ncol = col + dcol[i];
if(nrow >= 0 && ncol >= 0 && nrow < n && ncol < m &&
grid[nrow][ncol] != 'N' && ans[nrow][ncol] > ans[row][col] + 1){
ans[nrow][ncol] = ans[row][col] + 1;
q.add(new Pair(nrow, ncol));
}
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(grid[i][j] == 'H' && ans[i][j] == (n*m+1)){
ans[i][j] = -1;
}else if(grid[i][j] != 'H'){
ans[i][j] = 0;
}else{
ans[i][j] *= 2;
}
}
}
return ans;
}
}
OUTPUT:
This question is of GFG Weekly Interview Series - 72. And the above approach is my approach that may help you. I HOPE, IT HELPS!
Comments
Post a Comment