Covid Spread | Practice | GeeksforGeeks

Aterp is the head nurse at a city hospital. City hospital contains R*C number of wards and the structure of a hospital is in the form of a 2-D matrix.
Given a matrix of dimension R*C where each cell in the matrix can have values 0, 1, or 2 which has the following meaning:
0: Empty ward
1: Cells have uninfected patients
2: Cells have infected patients
An infected patient at ward [i,j] can infect other uninfected patient at indexes [i-1,j], [i+1,j], [i,j-1], [i,j+1] (up, down, left and right) in unit time. Help Aterp determine the minimum units of time after which there won't remain any uninfected patient i.e all patients would be infected. If all patients are not infected after infinite units of time then simply return -1.
 

Example 1:
Input:
3 5
2 1 0 2 1
1 0 1 2 1
1 0 0 2 1 
Output:
2
Explanation:
Patients at positions {0,0}, {0, 3}, {1, 3}
and {2, 3} will infect patient at {0, 1}, 
{1, 0},{0, 4}, {1, 2}, {1, 4}, {2, 4} during 1st 
unit time. And, during 2nd unit time, patient at 
{1, 0} will get infected and will infect patient 
at {2, 0}. Hence, total 2 unit of time is
required to infect all patients.
Example 2:
Input:
3 5
2 1 0 2 1
0 0 1 2 1
1 0 0 2 1
Output:
-1
Explanation:
All patients will not be infected.
 
Your Task:  
You don't need to read input or print anything. Your task is to complete the function helpaterp() which takes a 2-D Matrix hospital as input parameter and returns the minimum units of time in which all patients will be infected or -1 if it is impossible.
Expected Time Complexity: O(R*C)
Expected Auxiliary Space: O(R*C)

Constraints:
1  ≤  R,C ≤ 1000
0 ≤ mat[i][j] ≤ 2
+1
madhukartemba1 month ago
JAVA SOLUTION:
class Pair
{
    int x, y;
    Pair(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

//User function Template for Java

class Solution
{
     public int helpaterp(int[][] hospital) {
        
        Queue<Pair> queue = new ArrayDeque<>();
        
        int n = hospital.length;
        int m = hospital[0].length;
        
        int healthy_patients = 0;
        
        int total_patients = 0;
        
        for(int i=0; i<n; i++)
        {
            for(int j=0; j<m; j++)
            {
                if(hospital[i][j] == 1)
                {
                    healthy_patients++;
                    total_patients++;
                }
                else if(hospital[i][j] == 2)
                {
                    queue.add(new Pair(i, j));
                    total_patients++;
                }
                
            }
        }
        
        if(total_patients==healthy_patients) return -1;
        if(healthy_patients == 0) return 0;
        
        int dx[] = {1, 0, -1, 0};
        int dy[] = {0, 1, 0, -1};
        
        int time_units = 0;
        
        while(queue.isEmpty()==false && healthy_patients>0)
        {
            int queue_size = queue.size();
            
            time_units++;
            
            for(int j=0; j<queue_size; j++)
            {
                Pair p = queue.poll();
            
                for(int i=0; i<4; i++)
                {
                    int x = p.x + dx[i];
                    int y = p.y + dy[i];
                    
                    if(x>=0 && y>=0 && x<n && y<m)
                    {
                        if(hospital[x][y] == 1)
                        {
                            hospital[x][y] = 2;
                            healthy_patients--;
                            queue.add(new Pair(x, y));
                        }
                    }
                }
            }
            
        }
        
        if(healthy_patients==0) return time_units;
        
        return -1;
        
        
    }
}

0
seagullcode1 month ago
int helpaterp(vector<vector<int>> hospital)   {       //code here       int ans=0;       int dx[4]={1,-1,0,0};       int dy[4]={0,0,-1,1};              int r = hospital.size();       int c = hospital[0].size();       vector<vector<int>> level(r,vector<int>(c,INT_MAX));       vector<vector<int>> vis(r,vector<int>(c,0));       queue<pair<int,int>> q;              for(int i=0;i<r;i++){           for(int j=0;j<c;j++)           {               if(hospital[i][j]==2){                   level[i][j]=0;                   q.push({i,j});                   vis[i][j]=1;                           }               if(hospital[i][j]==0){                   level[i][j]=0;                   vis[i][j]=1;               }                                         }       }                            while(!q.empty()){           int x=q.front().first;           int y = q.front().second;           q.pop();           for(int ti=0;ti<4;ti++){              int tx = x+dx[ti];              int ty = y+dy[ti];                            if(tx>=0 && ty>=0 && tx<r && ty <c && !vis[tx][ty] && hospital[tx][ty]==1){                  vis[tx][ty]=1;                                  if(level[x][y]<level[tx][ty])                  level[tx][ty]=level[x][y]+1;                                    q.push({tx,ty});                             }                          }                  }              for(int ti=0;ti<r;ti++){           for(int tc=0;tc<c;tc++){               if(level[ti][tc]>ans)               ans=level[ti][tc];           }       }              if (ans==INT_MAX)       return-1;                    return ans;   }
0
tthakare731 month ago
//Java Solution
class Solution{
    
    public static class pair{
        int x, y, dist;
        pair(int a, int b, int distance){
            x = a;
            y = b;
            dist = distance;
        }
    }
    
    public int helpaterp(int[][] hospital) {
        int distance = 0, n = hospital.length, m = hospital[0].length;
        boolean[][] visited = new boolean[n][m];
        Queue<pair> PQ = new LinkedList<>();
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(hospital[i][j] == 2) {
                    PQ.add(new pair(i, j, 0));
                    visited[i][j] = true;
                }        
            }
        }
        
        int dx[] = {0, 0, -1, 1};
        int dy[] = {-1, 1, 0, 0};
        
        while(!PQ.isEmpty()){
            pair current = PQ.poll();
            int Cx = current.x, Cy = current.y, Cdist = current.dist;
            for(int i = 0; i < 4; i++){
            
                if(Cx+dx[i] < n && Cy+dy[i] < m && Cx+dx[i] >= 0 && Cy+dy[i] >= 0 && !visited[Cx+dx[i]][Cy+dy[i]] && hospital[Cx+dx[i]][Cy+dy[i]] == 1){
                    visited[Cx+dx[i]][Cy+dy[i]] = true;
                    hospital[Cx+dx[i]][Cy+dy[i]] = 2;
                    PQ.add(new pair(Cx+dx[i], Cy+dy[i], Cdist+1));
                    distance = Math.max(distance, Cdist+1);
                }
            }
        }
        
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(hospital[i][j] == 1) return -1;
            }
        }
        return distance;
    }
}
0
devashishbakare2 months ago
Java Solution
class pair{      int row;   int col;      public pair(int r, int c)   {       this.row = r;       this.col = c;   }}
class Solution{
   public int helpaterp(int[][] hospital) {              Queue<pair> qu = new LinkedList<pair>();              int cnt = 0 ;        int level= 0;              int ro = hospital.length;       int co = hospital[0].length;              int dim[][] = {{0,1}, {0,-1}, {-1,0}, {1,0}};              for(int i = 0 ; i < ro ; i++)           for(int j = 0; j < co ; j++)           {               if(hospital[i][j] != 0)                   cnt++;                              if(hospital[i][j] == 2)                   qu.offer(new pair(i, j));                         }              int count = 0;              while(!qu.isEmpty())       {           int size = qu.size();           count += size;                      for(int i = 0 ; i < size ; i++)           {               pair p = qu.poll();                              int x = p.row;               int y = p.col;                              for(int j[] : dim)               {                   int r = x + j[0];                   int c = y + j[1];                                      if(check(hospital, r, c, hospital.length, hospital[0].length) == true)                   {                       hospital[r][c] = 2;                       qu.offer(new pair(r, c));                   }               }           }                      if(!qu.isEmpty())               level++;                          }       if( count != cnt) return -1;           else           return level;    }   public static boolean check(int hospital[][], int row, int col, int n, int m)   {        if( row >= 0 && row < n && col >= 0 && col < m && hospital[row][col] == 1)       return true;              return false;          }} 
+1
kronizerdeltac2 months ago
JAVA SOLUTION:
class Solution{
     public int helpaterp(int[][] hospital) {
        int n = hospital.length, m = hospital[0].length;
        LinkedList<Integer> queue = new LinkedList<>();
        int infectedCount = 0, uninfectedCount = 0;
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                if(hospital[i][j] == 2) {
                    infectedCount++;
                    queue.addLast(i * m + j);
                } else if(hospital[i][j] == 1)
                    uninfectedCount++;
            }
        }
        
        if(infectedCount == 0)
            return -1;
            
        if(uninfectedCount == 0)
            return 0;
            
        int[][] dir = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int time = 0;
        while(queue.size() != 0) {
            int size = queue.size();
            while(size-- > 0) {
                int idx = queue.removeFirst();
                int sr = idx / m, sc = idx % m;
                
                for(int[] d : dir) {
                    int r = sr + d[0];
                    int c = sc + d[1];
                    
                    if(r >= 0 && c >= 0 && r < n && c < m && hospital[r][c] == 1) {
                        uninfectedCount--;
                        if(uninfectedCount == 0)
                            return time + 1;
                        hospital[r][c] = 2;
                        queue.addLast(r * m + c);
                    }
                }
            }
            time++;
        }
        return -1;
    }
}
+1
shyamprakash8072 months ago
Python solution using DFS:
Time Taken : 0.2/6.5
 
from collections import dequeclass Solution:   def helpaterp(self, hospital):       q = deque()       n, m = len(hospital), len(hospital[0])       for i in range(n):           for j in range(m):               if hospital[i][j] == 2:                   q.append([i,j])       c = 0       while len(q):           z = len(q)           flag = 0           for _ in range(z):               i, j = q.popleft()               if i-1>=0 and hospital[i-1][j]==1:                   hospital[i-1][j] = 2                   q.append([i-1,j])                   flag = 1               if i + 1<n and hospital[i+1][j]==1:                   hospital[i+1][j] = 2                   q.append([i+1, j])                   flag = 1               if j-1>=0 and hospital[i][j-1]==1:                   hospital[i][j-1]=2                   q.append([i,j-1])                   flag = 1               if j+1<m and hospital[i][j+1]==1:                   hospital[i][j+1] = 2                   q.append([i,j+1])                   flag = 1           if flag:               c += 1       for i in range(n):           for j in range(m):               if hospital[i][j] == 1:                   return -1       return c
0
shiva10902 months ago
 queue<pair<int,int>> q;   int n = hospital.size();
        int tot = 0 , count = 0 , minutes = 0;
        
        for(int i = 0; i < hospital.size(); i++)
        {
            for(int j = 0; j < hospital[0].size(); j++)
            {
                if(hospital[i][j] != 0){
                    tot++;
                }
                if(hospital[i][j] == 2){
                    q.push({i,j});
                }
            }
        }
        
        int dx[4] = {0,0,-1,1};
        int dy[4] = {1,-1,0,0};
        
        while(!q.empty())
        {
            int sz = q.size();
            count += sz;
            
            for(int j = 0; j < sz; j++)
            {
                int x = q.front().first ,  y = q.front().second;
                q.pop();
                
                for(int i = 0; i < 4; i++)
                {
                    int nx = x+dx[i] , ny = y+dy[i];
                    
                    if(nx < 0 || ny < 0 || nx >= n || ny >= hospital[0].size() || hospital[nx][ny] != 1)continue;
                    
                    hospital[nx][ny] = 2;
                    q.push({nx,ny});
                }
                
            }
             if(!q.empty())minutes++;
        }
        
        if(count != tot)return -1;
        return minutes;
0
roushank5592 months ago
int helpaterp(vector<vector<int>> hospital)
    {
        //code here
        int n=hospital.size();
        int m=hospital[0].size();
        
        int visited[n][m];
        int level[n][m];
        
        memset(level,0,sizeof level);
        memset(visited,0,sizeof visited);
        
        int ans=0;
        vector<pair<int,int>> moves = {
            {-1,0},{1,0},
            {0,-1},{0,1}
            
        };
        queue<pair<int,int>> q;
       // cout << "pass1\n";
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(hospital[i][j]==2){
                    
                    q.push({i,j});
                    
                    visited[i][j]=1;
                    
                    level[i][j]=0;
                }
            }
        }
       // cout << "pass2\n";
        
        while(q.size()>0)
        {
            auto parent = q.front();
            int x = parent.first;
            int y = parent.second;
            
            q.pop();
            for(auto mo : moves)
            {
                int childX = x+mo.first;
                int childY = y+mo.second;
                if(childX>=0 && childX < n &&
                   childY>=0 && childY < m && 
                   visited[childX][childY]==0 &&
                   hospital[childX][childY]==1)
                  {
                  hospital[childX][childY]=2;
                  
                  visited[childX][childY]=1;
                  
                  q.push({childX,childY});
                  level[childX][childY]=level[x][y]+1;
                  ans = max(ans,level[childX][childY]);
                  }
                  
            }
        }
        
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                //cout<<hospital[i][j]<<" ";
               if(hospital[i][j]==1)
               {
                   return -1;
               }
            }
            //cout<<endl;
        }
        
        return ans;
    }
+1
sahithkumarksrs3 months ago
int dx[4] = {0,0,1,-1};   int dy[4] = {1,-1,0,0};   int helpaterp(vector<vector<int>> hospital)   {       //code here       queue<pair<int,int>>q;            int count = 0;       int samay = 0;
       for(int i = 0;i<hospital.size();i++)       {           for(int j = 0;j<hospital[i].size();j++)           {               if(hospital[i][j] == 1)               {                   count++;               }               if(hospital[i][j] == 2)               {                   q.push({i,j});               }           }       }           while(!q.empty())       {           int k = q.size();           samay++;           for(int i = 0;i<k;i++)           {               int x = q.front().first;               int y = q.front().second;               q.pop();                              for(int k = 0;k<4;k++)               {                   int i = x + dx[k];                   int j = y + dy[k];                   if(i>=0 and j>=0 and i<hospital.size() and j<hospital[0].size() and hospital[i][j] == 1)                   {                       // cout<<i<<" x "<<j<<" y"<<endl;                       hospital[i][j] = 2;                       q.push({i,j});                       count--;                   }               }           }       }       if(count!=0)       return -1;       else       return samay-1;          }
-1
kiranrkuyate20213 months ago
 int dr[4][2] = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};
int bsf(queue<pair<int, pair<int, int>>> q, vector<vector<int>> &grid, vector<vector<bool>> &visited)
{
    int n = grid.size(), m = grid[0].size();
    int level = 0;
    int z = 0;
    while (!q.empty())
    {

        int myLevel = q.front().first;
        int i = q.front().second.first;
        int j = q.front().second.second;
        q.pop();
        if (visited[i][j])
            continue;
        visited[i][j] = true;
        for (int k = 0; k < 4; k++)
        {
            // cout << "pass3" << z++ << "\n";
            int dx = dr[k][0];
            int dy = dr[k][1];
            int nbri = i + dx;
            int nbrj = j + dy;
            if (nbri >= 0 && nbri < n && nbrj >= 0 && nbrj < m)
            {
                if (grid[nbri][nbrj] == 1)
                {
                    q.push({myLevel + 1, {nbri, nbrj}});
                }
                else if (grid[nbri][nbrj] == 2)
                {
                    q.push({myLevel, {nbri, nbrj}});
                }
            }
        }
        level = max(myLevel, level);
    }
    return level;
}

int helpaterp(vector<vector<int>> grid)
{
    int n = grid.size(), m = grid[0].size();
    int count = -1;
    vector<vector<bool>> visited(n, vector<bool>(m, false));
    queue<pair<int, pair<int, int>>> q;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            if (grid[i][j] == 2)
            {
                q.push({0, {i, j}});
                // cout<<"pass1\n";
            }
        }
    }
    count = max(count, bsf(q, grid, visited));
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            if (visited[i][j] == false && grid[i][j] == 1)
            {
                // cout << "pass2\n";
                count = -1;
                break;
            }
        }
    }
    return count;
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.