Leetcode200:
DFS的核心是不断的递归;BFS的核心是不断的加入队列,从队列中取出,然后弹出。
LeetCode200:

给你一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成。

此外,你可以假设该网格的四条边均被水包围。

DFS解法

  1. class Solution {
  2. public int numIslands(char[][] grid) {
  3. int m = grid.length;
  4. int n = grid[0].length;
  5. int count = 0;
  6. for (int i = 0; i < m; i++) {
  7. for (int j = 0; j < n; j++) {
  8. if (grid[i][j] == '1') {
  9. dfs(grid, i, j, m, n);
  10. count++;
  11. }
  12. }
  13. }
  14. return count;
  15. }
  16. private void dfs(char[][] grid, int i, int j, int m, int n) {
  17. if (i >= m || j >= n || i < 0 || j < 0) {
  18. return;
  19. }
  20. if (grid[i][j] == '0') {
  21. return;
  22. }
  23. grid[i][j] = '0';
  24. if (i + 1 < m) {
  25. dfs(grid, i + 1, j, m, n);
  26. }
  27. if (j + 1 < n) {
  28. dfs(grid, i, j + 1, m, n);
  29. }
  30. if (i - 1 >= 0) {
  31. dfs(grid, i - 1, j, m, n);
  32. }
  33. if (j - 1 >= 0) {
  34. dfs(grid, i, j - 1, m, n);
  35. }
  36. }
  37. }

BFS解法

  1. class Solution {
  2. public int numIslands(char[][] grid) {
  3. int count = 0;
  4. for(int i = 0; i < grid.length; i++) {
  5. for(int j = 0; j < grid[0].length; j++) {
  6. if(grid[i][j] == '1'){
  7. bfs(grid, i, j);
  8. count++;
  9. }
  10. }
  11. }
  12. return count;
  13. }
  14. private void bfs(char[][] grid, int i, int j){
  15. Queue<int[]> list = new LinkedList<>();
  16. list.add(new int[] { i, j });
  17. while(!list.isEmpty()){
  18. int[] cur = list.remove();
  19. i = cur[0]; j = cur[1];
  20. if(0 <= i && i < grid.length && 0 <= j && j < grid[0].length && grid[i][j] == '1') {
  21. grid[i][j] = '0';
  22. list.add(new int[] { i + 1, j });
  23. list.add(new int[] { i - 1, j });
  24. list.add(new int[] { i, j + 1 });
  25. list.add(new int[] { i, j - 1 });
  26. }
  27. }
  28. }
  29. }

参考文献

  1. https://leetcode-cn.com/problems/number-of-islands/solution/number-of-islands-shen-du-you-xian-bian-li-dfs-or-/