shriyanshi24jindal

Islands and Treasure

Mar 29th, 2026
121
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 15.21 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. // similar to Distance of nearest cell having 1
  16. public void islandsAndTreasure(int[][] grid) {
  17. ArrayList<ArrayList<Integer>> res = new ArrayList<>();
  18.  
  19. int n = grid.length;
  20. int m = grid[0].length;
  21.  
  22. Queue<Pair> q = new LinkedList<>();
  23.  
  24. // visited array to mark which all land cells are visited
  25. boolean[][] visited = new boolean[n][m];
  26. // distance matrix that will store the nearest distance of 0's from land cells
  27. int[][] distance = new int[n][m];
  28.  
  29. // step-1 adding all those indices into queue where we have as 0's and mark them visited
  30. for(int i=0; i<n; i++)
  31. {
  32. for(int j=0; j<m; j++)
  33. {
  34. if(grid[i][j] == 0)
  35. {
  36. q.add(new Pair(i,j,0));
  37. visited[i][j] = true;
  38. distance[i][j] = 0;
  39. }
  40. else if(grid[i][j] == -1)
  41. distance[i][j] = -1;
  42. }
  43. }
  44.  
  45. int[] deltaRow = {-1,1,0,0};
  46. int[] deltaCol = {0,0,1,-1};
  47.  
  48. // step-2 traverse the stored indices in queue and check for neighbour 0's
  49. while(!q.isEmpty())
  50. {
  51. Pair pair = q.poll();
  52. int row = pair.first;
  53. int col = pair.second;
  54. int step = pair.step;
  55.  
  56. for(int i=0; i<4; i++)
  57. {
  58. int nRow = row + deltaRow[i];
  59. int nCol = col + deltaCol[i];
  60.  
  61. if(nRow >=0 && nRow < n && nCol >= 0 && nCol < m)
  62. {
  63. // expand to land cells
  64. if(visited[nRow][nCol] == false && grid[nRow][nCol] == 2147483647)
  65. {
  66. q.add(new Pair(nRow, nCol, step+1));
  67. visited[nRow][nCol] = true;
  68. distance[nRow][nCol] = step+1;
  69. }
  70. }
  71. }
  72. }
  73.  
  74. for(int i=0; i<n; i++)
  75. {
  76. for(int j=0; j<m; j++)
  77. {
  78. grid[i][j] = distance[i][j];
  79. }
  80. }
  81. }
  82. }
RAW Paste Data Copied