Distance of nearest cell having 1 | Practice | GeeksforGeeks

Given a binary grid. Find the distance of nearest 1 in the grid for each cell.
The distance is calculated as |i1 – i2| + |j1 – j2|, where i1, j1 are the row number and column number of the current cell and i2, j2 are the row number and column number of the nearest cell having value 1.
 
Example 1:
Input: grid = {{0,1,1,0},{1,1,0,0},{0,0,1,1}}
Output: {{1,0,0,1},{0,0,1,1},{1,1,0,0}}
Explanation: The grid is-
0 1 1 0 
1 1 0 0 
0 0 1 1 
0's at (0,0), (0,3), (1,2), (1,3), (2,0) and
(2,1) are at a distance of 1 from 1's at (0,1),
(0,2), (0,2), (2,3), (1,0) and (1,1)
respectively.

Example 2:
Input: grid = {{1,0,1},{1,1,0},{1,0,0}}
Output: {{0,1,0},{0,0,1},{0,1,2}}
Explanation: The grid is-
1 0 1
1 1 0
1 0 0
0's at (0,1), (1,2), (2,1) and (2,2) are at a 
distance of 1, 1, 1 and 2 from 1's at (0,0),
(0,2), (2,0) and (1,1) respectively.

 
Yout Task:
You don't need to read or print anything, Your task is to complete the function nearest() which takes grid as input parameter and returns a matrix of same dimensions where the value at index (i, j) in the resultant matrix signifies the minimum distance of 1 in the matrix from grid[i][j].
 
Expected Time Complexity: O(n*m)
Expected Auxiliary Space: O(n*m)
Constraints:
1 ≤ n, m ≤ 500
0
shilsoumyadip1 week ago
 vector<vector<int>>nearest(vector<vector<int>>grid){    // Code here    int row = grid.size();    int column = grid[0].size();    queue<pair<int,int>> q ;    vector<vector<int>>ans(row,vector<int>(column,INT_MAX));        for(int i=0;i<row;i++)    {        for(int j=0;j<column;j++)        {            if(grid[i][j] == 1)            {                q.push({i,j});                ans[i][j] = 0;            }        }    }        while(!q.empty())    {        int i = q.front().first;        int j = q.front().second;                   if( (i - 1) >= 0  and ans[i][j] + 1 < ans[i-1][j])        {            ans[i-1][j] = ans[i][j] + 1 ;            q.push({i-1,j});        }                if((j - 1) >= 0  and ans[i][j] + 1 < ans[i][j-1])        {            ans[i][j-1] = ans[i][j] + 1 ;            q.push({i,j-1});        }                if((i + 1) < row  and ans[i][j] + 1 < ans[i+1][j])        {            ans[i+1][j] = ans[i][j] + 1 ;            q.push({i+1,j});        }                if((j + 1) < column  and ans[i][j] + 1 < ans[i][j+1])        {             ans[i][j+1] = ans[i][j] + 1 ;             q.push({i,j+1});        }        q.pop();    }    return ans;}};
+2
saurabhsathe12341 month ago
C++ : 0.6ms
 
Watch this video for concept ,
 
https://www.youtube.com/watch?v=wtRT9G42g4g
 
bool check(int i , int j ,int n , int m)
    {
        if(i < 0 || j < 0 || i >= n || j >= m )
           return false ;
           
          return true;
    }
    
    
	vector<vector<int>>nearest(vector<vector<int>>grid)
	{
	    int n = grid.size();
	    int m = grid[0].size();
	    queue<pair<int,int>> q ;
	    vector<vector<int>>ans(n,vector<int>(m,-1));
	    
	    for(int i=0;i<n;i++)
	    {
	        for(int j=0;j<m;j++)
	        {
	            if(grid[i][j] == 1)
	            {
	                q.push({i,j});
	                ans[i][j] = 0;
	            }
	        }
	    }
	    
	    while(!q.empty())
	    {
	        int i = q.front().first;
	        int j = q.front().second;
	        q.pop();
	        
	        if(check(i-1,j,n,m) && ans[i-1][j] == -1)
	        {
	            ans[i-1][j] = ans[i][j] + 1 ;
	            q.push({i-1,j});
	        }
	        
	        if(check(i,j-1,n,m) && ans[i][j-1] == -1)
	        {
	            ans[i][j-1] = ans[i][j] + 1 ;
	            q.push({i,j-1});
	        }
	        
	        if(check(i,j+1,n,m) && ans[i][j+1] == -1)
	        {
	            ans[i][j+1] = ans[i][j] + 1 ;
	            q.push({i,j+1});
	        }
	        
	        if(check(i+1,j,n,m) && ans[i+1][j] == -1)
	        {
	            ans[i+1][j] = ans[i][j] + 1 ;
	            q.push({i+1,j});
	        }
	    }
	    return ans;
	}
0
milindprajapatmst191 month ago
HELP!! Why segmentation fault?? I tried to ran it in my local machine via visual studio community, which uses microsoft c++. Also, I tried at some random online ide, which uses gcc compiler. On both the platforms, it is working fine!!

int dx[] = {-1,  0, 1, 0};
int dy[] = { 0, -1, 0, 1};

# define pi pair<int, int>
# define mp make_pair
# define f first
# define s second

class Solution {
    public:
    // multi-source bfs 
    vector<vector<int>> nearest(vector<vector<int>>& grid) {
        int n = grid.size(), m = grid[0].size();
        vector<vector<int>> dist(n, vector<int>(m, -1));
        queue<pi> q;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == 1) {
                    dist[i][j] = 0;
                    q.push(mp(i, j));
                }
            }
        }
        while (!q.empty()) {
            int sz = q.size();
            while(sz--) {
                pi& p = q.front();
                q.pop();
                for (int k = 0; k < 4; k++) {
                    int i = p.f + dx[k], j = p.s + dy[k];
                    if (0 <= i && i < n && 0 <= j && j < m && dist[i][j] == -1) {
                        q.push(mp(i, j));
                        dist[i][j] = dist[p.f][p.s] + 1;
                    }
                }
            }
        }
        return dist;
    }
};
+1
himanshukug19cs1 month ago
java solution
 class pair{       int x;       int y;       pair(int x,int y){           this.x=x;           this.y=y;       }   }   boolean[][] vis;   boolean isValid(pair p,int[][] grid){       int i=grid.length;       int j=grid[0].length;       if(p.x<0||p.y<0||p.x>=i||p.y>=j||vis[p.x][p.y]==true||grid[p.x][p.y]==1)           return false;       return true;       }   public int[][] nearest(int[][] grid)   {       // Code here       vis= new boolean[grid.length][grid[0].length];       int[][] ans = new int[grid.length][grid[0].length];       ArrayDeque<pair> dq = new ArrayDeque<>();       for(int i=0;i<grid.length;i++){           for(int j=0;j<grid[0].length;j++){               if(grid[i][j]==1){                   ans[i][j]=0;                   dq.add(new pair(i,j));                   vis[i][j]=true;               }           }       }       int[] xarr={-1,0,1,0};       int[] yarr={-0,1,0,-1};              while(!dq.isEmpty()){           pair re = dq.remove();                      for(int i=0;i<4;i++){               pair p = new pair(re.x+xarr[i],re.y+yarr[i]);               if(isValid(p,grid)){                   vis[p.x][p.y]=true;                   ans[p.x][p.y]=Math.abs(re.x-p.x)+Math.abs(re.y-p.y)+ans[re.x][re.y];                   dq.add(p);               }           }                  }       return ans;   }
0
tthakare732 months ago
//Java Solution --> hint use BFS
class Solution
{
    public static class pair{
        int i, j;
        pair(int a, int b){
            i = a;
            j = b;
        }
    }
    
    public static boolean checkSafe(int i, int j, int m, int n, int[][] result, int preI, int preJ){
        return (i >= 0 && j >= 0 && i < m && j < n && result[preI][preJ] < result[i][j]);
    }
    //Function to find distance of nearest 1 in the grid for each cell.
    public int[][] nearest(int[][] grid){
        // Code here
        int m = grid.length;
        int n = grid[0].length;
        
        int[][] result = new int[m][n];
        for(int i = 0; i < m; i++){
            Arrays.fill(result[i], Integer.MAX_VALUE);
        }
        
        Queue<pair> pq = new LinkedList<>();
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(grid[i][j] == 1){
                    result[i][j] = 0;
                    pq.add(new pair(i, j));
                }
            }
        }
        
        int x[] = {1, -1, 0, 0};
        int y[] = {0, 0, -1, 1};
        while(!pq.isEmpty()){
            pair current = pq.poll();
            int curtI = current.i;
            int curtJ = current.j;
            for(int i = 0; i < 4; i++){
                if(checkSafe(curtI+x[i], curtJ+y[i], m, n, result, curtI, curtJ)){
                    result[curtI+x[i]][curtJ+y[i]] = result[curtI][curtJ]+1;
                    pq.add(new pair(curtI+x[i], curtJ+y[i]));
                }
            }
        }
        
        return result;
    }
}
+2
siddhant072 months ago
//BFS based solution to find minimum distance in the grid
    bool isValid(int x, int y, int rows, int cols){
        if(x < 0 || x >= rows || y < 0 || y>= cols){
            return false;
        }
        return true;
    }
    
	vector<vector<int>>nearest(vector<vector<int>>grid)
	{
	    //This is the based on Breadth First Search
	    int rows = grid.size();
	    int cols = grid[0].size();
	    queue<pair<int, int>> q;
	    vector<vector<bool>> visited;
	    vector<vector<int>> ans;
	    for(int i = 0; i < rows; i++){
	        vector<bool> v (cols, false);
	        vector<int> a (cols, INT_MAX);
	        visited.push_back(v);
	        ans.push_back(a);
	    }
	    for(int i = 0; i < rows; i++){
	        for(int j = 0; j < cols; j++){
	            if(grid[i][j] == 1){
	                visited[i][j] = true;
	                ans[i][j] = 0;
	                q.push({i, j});
	            }
	        }
	    }
	    int dx[4] = {0, 1, 0, -1};
	    int dy[4] = {1, 0, -1, 0};
	    while(q.empty() == false){
	        int x = q.front().first;
	        int y = q.front().second;
	        q.pop();
	        int currDist = ans[x][y];
	        for(int i = 0; i < 4; i++){
	            int xdx = x + dx[i];
	            int ydy = y + dy[i];
	            if(isValid(xdx, ydy, rows, cols)){
	            if(visited[xdx][ydy] == false){
	                visited[xdx][ydy] = true;
	                q.push({xdx, ydy});
	                ans[xdx][ydy] = currDist + 1;
	            }
	            }
	        }
	    }
	    return ans;
	}
0
maheshahirwar2042 months ago
Java Solution 
 
class Solution{   static class Pair{       int x,y;       Pair(int x,int y){           this.x=x;           this.y=y;       }   }   //Function to find distance of nearest 1 in the grid for each cell.   public int[][] nearest(int[][] grid)   {       int n=grid.length;       int m=grid[0].length;      Queue<Pair>q=new LinkedList<Pair>();      int a=Integer.MAX_VALUE;      int[][]ans=new int[n][m];      ans=fill(ans,a);      for(int i=0;i<n;i++){          for(int j=0;j<m;j++){              if(grid[i][j]==1){                  ans[i][j]=0;                  q.add(new Pair(i,j));              }          }      }      while(!q.isEmpty()){          Pair p=q.poll();          int i=p.x;          int j=p.y;          if((i-1)>=0&&ans[i][j]+1<ans[i-1][j]){              ans[i-1][j]=ans[i][j]+1;              q.add(new Pair(i-1,j));          }           if((j-1)>=0&&ans[i][j]+1<ans[i][j-1]){              ans[i][j-1]=ans[i][j]+1;              q.add(new Pair(i,j-1));          }           if((i+1)>=0&&i+1<n&&ans[i][j]+1<ans[i+1][j]){              ans[i+1][j]=ans[i][j]+1;              q.add(new Pair(i+1,j));          }           if((j+1)>=0&&j+1<m&&ans[i][j]+1<ans[i][j+1]){              ans[i][j+1]=ans[i][j]+1;              q.add(new Pair(i,j+1));          }      }      return ans;   }   public int[][] fill(int [][]ans,int a){       for(int i=0;i<ans.length;i++){           for(int j=0;j<ans[0].length;j++){               ans[i][j]=a;           }       }       return ans;   }}
-1
45mzzbhoest5k5060ff1se8zbxbntzof9sjy5d1e3 months ago
//Solution without creating queue and single traversal of grid. We check closest cells for 1 first. 
vector<vector<int>>nearest(vector<vector<int>>grid){   //d represents distance    int d=1;    int r=grid.size();    int c=grid[0].size();    int m,n,flag=0;    vector<vector<int>> g=grid;    for(int i=0;i<r;i++){        for(int j=0;j<c;j++){            d=1;            flag=0;            if(grid[i][j]==1)               g[i][j]=0;            else{                while(d<=(r+c-2)){                                        //if(i+d < r)                    for(m=i;m<=min(i+d,r-1);m++){                        n=d-abs(m-i)+j;                        if(n<c && grid[m][n]==1)                        {                            g[i][j]=d;                            flag=1;                            break;                        }                        else{                            n=abs(d-abs(m-i)-j);                            if(n<c && grid[m][n]==1){                                g[i][j]=d;                                flag=1;                                break;                            }                        }                    }                                        if(flag==0){                       for(m=i;m>=max(i-d,0);m--){                        n=d-abs(m-i)+j;                        if(n<c && grid[m][n]==1)                        {                            g[i][j]=d;                            flag=1;                            break;                        }                        else{                            n=abs(d-abs(m-i)-j);                            if(n<c && grid[m][n]==1){                                g[i][j]=d;                                flag=1;                                break;                            }                        }                       }                    }                                        if(flag==1)                       break;                                        d++;                }            }        }    }    return g;}
0
mufaddalshakir553 months ago
C++ Beast BFS
	vector<vector<int>>nearest(vector<vector<int>>grid)
	{
	    queue<pair<int,pair<int,int>>> q;
	    int counter = 0;
	    int n = grid.size();
	    int m = grid[0].size();
	    
	    for(int i=0;i<n;i++){
	        for(int j=0;j<m;j++){
	            
	            if(grid[i][j] == 0){
	                grid[i][j] = INT_MAX;
	                counter++;
	            }else{
	                grid[i][j] = 0;
	                q.push({0,{i,j}});
	            }
	            
	        }
	    }
	    
	    
	    while(!q.empty()){
	        
	        auto top = q.front(); q.pop();
	        int dist = top.first;
	        int i  = top.second.first;
	        int j  = top.second.second;
	        
	        int arr[] = {0,1,0,-1,0};
	        for(int k=0;k<4;k++){
	            int x = i+arr[k];
	            int y = j+arr[k+1];
	            
	            if(x>=0 && x<n && y>=0 && y<m && grid[x][y]>0){
	                if(grid[x][y]>dist+1){
	                   grid[x][y]=dist+1;
	                   q.push({grid[x][y],{x,y}});
	                   //if(--counter==0) return grid;
	                }
	            }
	        }
	        
	        int arr2[] = {1,1,-1,-1,1};
	        for(int k=0;k<4;k++){
	            int x = i+arr2[k];
	            int y = j+arr2[k+1];
	            
	            if(x>=0 && x<n && y>=0 && y<m && grid[x][y]>0){
	                if(grid[x][y]>dist+2){
	                   grid[x][y]=dist+2;
	                   q.push({grid[x][y],{x,y}});
	                   //if(--counter==0) return grid;
	                }
	            }
	        }
	        
	    }
	    
	    return grid;
	}
};
+1
abhiiishek073 months ago
 vector<vector<int>>nearest(vector<vector<int>>grid){    // Code here    int n=grid.size();    int m=grid[0].size();    vector<vector<int>> dist(n,vector<int>(m,INT_MAX));    queue<pair<int,int>> q;    for(int i=0;i<n;i++)    {        for(int j=0;j<m;j++)        {           if(grid[i][j]==1)           {             dist[i][j]=0;             q.push({i,j});           }        }    }    while(!q.empty())    {        int i=q.front().first;        int j=q.front().second;        q.pop();        if(i+1<n && dist[i+1][j]> 1+dist[i][j])        {           dist[i+1][j]=1+dist[i][j];           q.push({i+1,j});        }        if(i-1>=0 && dist[i-1][j] > 1+dist[i][j])        {            dist[i-1][j]=1+dist[i][j];            q.push({i-1,j});        }        if(j-1>=0 && dist[i][j-1]>1+dist[i][j])        {            dist[i][j-1]=1+dist[i][j];            q.push({i,j-1});        }        if(j+1<m && dist[i][j+1]>1+dist[i][j])        {            dist[i][j+1]=1+dist[i][j];            q.push({i,j+1});        }    }    return dist;}
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.