HOT100 图论
1.岛屿数量
链接:200. 岛屿数量 - 力扣(LeetCode)
代码:
法1:DFS:其实就是找连通图的个数
Java
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
| class Solution { int m, n;
public int numIslands(char[][] grid) { if (grid.length == 0) { return 0; }
m = grid.length; n = grid[0].length;
int ans = 0;
for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) {
if (grid[i][j] == '1') {
dfs(grid, i, j);
++ans; } } }
return ans; }
private void dfs(char[][] grid, int i, int j) { if (i < 0 || i == m || j < 0 || j == n || grid[i][j] == '6' || grid[i][j] == '0') { return; }
grid[i][j] = '6';
dfs(grid, i - 1, j);
dfs(grid, i + 1, j);
dfs(grid, i, j - 1);
dfs(grid, i, j + 1); } }
|
法2:BFS
Java
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
| class Solution { int m, n;
public int numIslands(char[][] grid) { if (grid.length == 0) { return 0; }
m = grid.length; n = grid[0].length;
int ans = 0;
int[][] dirs = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') { ans++;
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[] { i, j });
grid[i][j] = '0';
while (!queue.isEmpty()) { int[] cur = queue.poll(); int x = cur[0]; int y = cur[1];
for (int[] dir : dirs) { int nx = x + dir[0]; int ny = y + dir[1];
if (nx < 0 || nx >= m || ny < 0 || ny >= n) { continue; }
if (grid[nx][ny] == '1') { queue.offer(new int[] { nx, ny });
grid[nx][ny] = '0'; } } } } } }
return ans; } }
|
法3:栈DFS
Java
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
| class Solution { int m, n;
public int numIslands(char[][] grid) { if (grid.length == 0) { return 0; }
m = grid.length; n = grid[0].length;
int ans = 0;
int[][] dirs = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') { ans++;
Deque<int[]> stack = new ArrayDeque<>(); stack.push(new int[] { i, j });
grid[i][j] = '0';
while (!stack.isEmpty()) { int[] cur = stack.pop(); int x = cur[0]; int y = cur[1];
for (int[] dir : dirs) { int nx = x + dir[0]; int ny = y + dir[1];
if (nx < 0 || nx >= m || ny < 0 || ny >= n) { continue; }
if (grid[nx][ny] == '1') { stack.push(new int[] { nx, ny }); grid[nx][ny] = '0'; } } } } } }
return ans; } }
|
法4:并查集
Java
评论区
欢迎留下你的想法评论系统还没有接入配置,界面已经预留好了。