public static void bfs(char[][] grid, boolean[][] visit, int i, int j) { Queue<int[]> queue = new LinkedList<int[]>(); queue.add(new int[] { i, j }); int[][] directions = new int[][] { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } }; while (queue.size() > 0) { int size = queue.size(); int[] val = queue.poll(); for (int[] dir : directions) { int row = val[0] + dir[0]; int col = val[1] + dir[1]; boolean index = (row < grid.length) && (col < grid[0].length) && (row >= 0) && (col >= 0); if (index && !visit[row][col] && grid[row][col] == '1') { visit[row][col] = true; queue.add(new int[] { row, col }); } } } result += 1; }