1. 程式人生 > >leetcode695+最大島嶼,典型DFS

leetcode695+最大島嶼,典型DFS

https://leetcode.com/problems/max-area-of-island/description/

class Solution {
public:
    int result = 0;
    void dfs(int x, int y, vector<vector<int>>&grid, int& num)
    {
        if((x<0)||(y<0)||(x>=grid.size())||(y>=grid[0].size())) return;
        else if(grid[x][y]==1){
            grid[x][y] = 0;
            num+=1;
            dfs(x-1,y,grid,num);
            dfs(x+1,y,grid,num);
            dfs(x,y-1,grid,num);
            dfs(x,y+1,grid,num);
        }
    }
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        if(grid.size()==0) return 0;
        int row = grid.size(), col = grid[0].size(),num=0;
        for(int i=0; i<row; i++){
            for(int j=0; j<col; j++){
                if(grid[i][j]==1){
                    num = 0;
                    dfs(i, j, grid,num);
                    result = max(result, num);
                }
            }
        }
        return result;
    }
};