Ref: https://pdai.tech/md/algorithm/alg-core-search.html

广度优先搜索(Depth-First Search,DFS)

2.经典案例

2.1 岛屿连通面积

Ref: https://leetcode-cn.com/problems/max-area-of-island/
image.png

  1. private int m, n;
  2. private int[][] direction = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
  3. public int maxAreaOfIsland(int[][] grid) {
  4. if (grid == null || grid.length == 0) {
  5. return 0;
  6. }
  7. m = grid.length;
  8. n = grid[0].length;
  9. int maxArea = 0;
  10. for (int i = 0; i < m; i++) {
  11. for (int j = 0; j < n; j++) {
  12. maxArea = Math.max(maxArea, dfs(grid, i, j));
  13. }
  14. }
  15. return maxArea;
  16. }
  17. private int dfs(int[][] grid, int r, int c) {
  18. if (r < 0 || r >= m || c < 0 || c >= n || grid[r][c] == 0) {
  19. return 0;
  20. }
  21. grid[r][c] = 0;
  22. int area = 1;
  23. for (int[] d : direction) {
  24. area += dfs(grid, r + d[0], c + d[1]);
  25. }
  26. return area;
  27. }