shriyanshi24jindal

Distance of nearest cell having 1

Mar 29th, 2026
102
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 15.11 KB | None | 0 0
  1. class Pair
  2. {
  3. int first;
  4. int second;
  5. int step;
  6. Pair(int first, int second, int step)
  7. {
  8. this.first = first;
  9. this.second = second;
  10. this.step = step;
  11. }
  12. }
  13.  
  14. class Solution {
  15. public ArrayList<ArrayList<Integer>> nearest(int[][] grid) {
  16. ArrayList<ArrayList<Integer>> res = new ArrayList<>();
  17.  
  18. int n = grid.length;
  19. int m = grid[0].length;
  20.  
  21. Queue<Pair> q = new LinkedList<>();
  22.  
  23. // visited array to mark which all 0's are visited
  24. boolean[][] visited = new boolean[n][m];
  25. // distance matrix that will store the nearest distance of 1's
  26. int[][] distance = new int[n][m];
  27.  
  28. // step-1 adding all those indices into queue where we have as 1 and mark them visited
  29. for(int i=0; i<n; i++)
  30. {
  31. for(int j=0; j<m; j++)
  32. {
  33. if(grid[i][j] == 1)
  34. {
  35. q.add(new Pair(i,j,0));
  36. visited[i][j] = true;
  37. distance[i][j] = 0;
  38. }
  39. }
  40. }
  41.  
  42. int[] deltaRow = {-1,1,0,0};
  43. int[] deltaCol = {0,0,1,-1};
  44.  
  45. // step-2 traverse the stored indices in queue and check for neighbour 0's
  46. while(!q.isEmpty())
  47. {
  48. Pair pair = q.poll();
  49. int row = pair.first;
  50. int col = pair.second;
  51. int step = pair.step;
  52.  
  53. // checking in all 4-directions
  54. for(int i=0; i<4; i++)
  55. {
  56. int nRow = row + deltaRow[i];
  57. int nCol = col + deltaCol[i];
  58.  
  59. if(nRow >=0 && nRow < n && nCol >=0 && nCol < m)
  60. {
  61. if(grid[nRow][nCol] == 0 && !visited[nRow][nCol])
  62. {
  63. q.add(new Pair(nRow, nCol, step+1));
  64. visited[nRow][nCol] = true;
  65. distance[nRow][nCol] = step+1;
  66. }
  67. }
  68. }
  69. }
  70.  
  71. // Step-3 convert the distance matrix into resulant array list
  72. for(int i=0; i<n; i++)
  73. {
  74. ArrayList<Integer> rowList = new ArrayList<>();
  75. for(int j=0; j<m; j++)
  76. {
  77. rowList.add(distance[i][j]);
  78. }
  79. res.add(rowList);
  80. }
  81. return res;
  82. }
  83. }
RAW Paste Data Copied