1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| import java.util.ArrayList; import java.util.HashSet; import java.util.Map; import java.util.Set;
public class _200岛屿数量 {
public int numIslands_color(char[][] grid) { rows = grid.length; columns = grid[0].length; cnt = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { dfs(grid, i, j, true); } } return cnt; }
private void dfs(char[][] grid, int i, int j, boolean isStart) { if (i < 0 || i >= rows || j < 0 || j >= columns || grid[i][j] != '1') { return; } if (isStart) { cnt++; } grid[i][j] = '2'; dfs(grid, i - 1, j, false); dfs(grid, i + 1, j, false); dfs(grid, i, j - 1, false); dfs(grid, i, j + 1, false); }
public int numIslands(char[][] grid) { Set<String> set = new HashSet<>(); rows = grid.length; columns = grid[0].length; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (grid[i][j] == '1') { set.add(i + "," + j); } } }
int cnt = 0; while (!set.isEmpty()) { String key = new ArrayList<>(set).getFirst(); dfs(grid, set, key); cnt++; } return cnt; }
int rows, columns, cnt;
private void dfs(char[][] grid, Set<String> set, String key) { set.remove(key); String[] split = key.split(","); int i = Integer.parseInt(split[0]), j = Integer.parseInt(split[1]); String key1 = (i - 1) + "," + j; String key2 = (i + 1) + "," + j; String key3 = i + "," + (j - 1); String key4 = i + "," + (j + 1); if (set.contains(key1)) { dfs(grid, set, key1); } if (set.contains(key2)) { dfs(grid, set, key2); } if (set.contains(key3)) { dfs(grid, set, key3); } if (set.contains(key4)) { dfs(grid, set, key4); } }
public static void main(String[] args) { _200岛屿数量 island = new _200岛屿数量();
System.out.println(island.numIslands(new char[][]{ {'1', '1', '1'}, {'1', '0', '1'}, {'1', '1', '1'} })); } }
|