publicintnumIslands(char[][] grid) { intm= grid.length, n = grid[0].length;
intlandCount=0; for (inti=0; i < m; i++) { for (intj=0; j < n; j++) { if (grid[i][j] == '1') { dfs(grid, m, n, i, j); landCount++; } } }
return landCount; }
privatevoiddfs(char[][] grid, int m, int n, int i, int j) { grid[i][j] = '0'; for (int[] direction : DIRECTIONS) { intnextI= i + direction[0]; intnextJ= j + direction[1]; if (nextI >= 0 && nextI < m && nextJ >= 0 && nextJ < n && grid[nextI][nextJ] == '1') { dfs(grid, m, n, nextI, nextJ); } } } }
publicintnumIslands(char[][] grid) { intm= grid.length, n = grid[0].length;
intlandCount=0; for (inti=0; i < m; i++) { for (intj=0; j < n; j++) { if (grid[i][j] == '1') { bfs(grid, m, n, i, j); landCount++; } } }
return landCount; }
privatevoidbfs(char[][] grid, int m, int n, int i, int j) { Queue<int[]> queue = newLinkedList<>(); // 队列中的点为已经清除了陆地状态的点 grid[i][j] = '0'; // 注意在入队前标记以防止重复入队 queue.offer(newint[]{i, j});
while (!queue.isEmpty()) { int[] point = queue.poll(); for (int[] direction : DIRECTIONS) { intnextI= point[0] + direction[0]; intnextJ= point[1] + direction[1];
if (nextI < 0 || nextI >= m || nextJ < 0 || nextJ >= n || grid[nextI][nextJ] == '0') { continue; }