class Pair { int first; int second; int step; Pair(int first, int second, int step) { this.first = first; this.second = second; this.step = step; } } class Solution { public ArrayList> nearest(int[][] grid) { ArrayList> res = new ArrayList<>(); int n = grid.length; int m = grid[0].length; Queue q = new LinkedList<>(); // visited array to mark which all 0's are visited boolean[][] visited = new boolean[n][m]; // distance matrix that will store the nearest distance of 1's int[][] distance = new int[n][m]; // step-1 adding all those indices into queue where we have as 1 and mark them visited for(int i=0; i=0 && nRow < n && nCol >=0 && nCol < m) { if(grid[nRow][nCol] == 0 && !visited[nRow][nCol]) { q.add(new Pair(nRow, nCol, step+1)); visited[nRow][nCol] = true; distance[nRow][nCol] = step+1; } } } } // Step-3 convert the distance matrix into resulant array list for(int i=0; i rowList = new ArrayList<>(); for(int j=0; j