[LeetCode 695] Max Area of Island

1. DFS 

Starting from a node, when using DFS to traverse a graph, the nodes that can be traversed are all reachable from the initial node. DFS is often used to solve this kind of reachability problem.

The following issues need to be considered when the program implements DFS:

  • Stack: Use the stack to save the current node information, and continue to traverse the current node when traversing the new node returns. You can use recursive stacks (recursive function calls).
  • Marking: As with BFS, it is also necessary to mark nodes that have been traversed.
     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 
     4 class Solution {
     5 public:
     6     int maxAreaOfIsland(vector<vector<int>>& grid) {   
     7         int res = 0;
     8         for(int i = 0;i<grid.size();++i)
     9            for(int j = 0; j< grid[0].size();++j)
    10            {
    11                res =max (dfs (grid, i, j), res);
     12             }
     13          return res;
     14      }
     15  private :
     16      int dfs (vector <vector < int >> & grid, int x, int y)
     17      {
     18          if ( ! (X> = 0 && X <grid.size () && Y> = 0 && Y <Grid [ 0 ] .size ())) return  0 ; // first determine the table array, preventing the array bounds errors 
    . 19          IF (Grid [ x] [y] == 0 ) return  0 ;
     20          grid [x] [y] =0 ; // Reuse grid [] [] as a marker array to reduce the space complexity to O (1) 
    21          return  1 + dfs (grid, x, y- 1 ) + dfs (grid, x, y + 1 ) + dfs (grid, x- 1 , y) + dfs (grid, x + 1 , y);
     22      }
     23 };

Guess you like

Origin www.cnblogs.com/wangxf2019/p/12681500.html