publicintnumIslands(char[][] grid){ if (grid == null || grid.length == 0) return count; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] == '1') { dfs(grid, i, j); count++; } } } return count; }
privatevoiddfs(char[][] grid, int i, int j){ grid[i][j] = '0'; for (int k = 0; k < 4; k++) { int diri = i + directions[k][0]; int dirj = j + directions[k][1]; if (diri >= 0 && diri < grid.length && dirj >= 0 && dirj < grid[0].length && grid[diri][dirj] == '1') { dfs(grid, diri, dirj); } } }