Leetcode#695. Max Area of Island(島の最大面積、深さdfs)


タイトル
Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
Example 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
 [0,0,0,0,0,0,0,1,1,1,0,0,0],
 [0,1,1,0,1,0,0,0,0,0,0,0,0],
 [0,1,0,0,1,1,0,0,1,0,1,0,0],
 [0,1,0,0,1,1,0,0,1,1,1,0,0],
 [0,0,0,0,0,0,0,0,0,0,1,0,0],
 [0,0,0,0,0,0,0,1,1,1,0,0,0],
 [0,0,0,0,0,0,0,1,1,0,0,0,0]]

Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
Example 2:
[[0,0,0,0,0,0,0,0]]

Given the above grid, return 0.

Note: The length of each dimension in the given grid does not exceed 50.
に言及
2次元配列をあげて、1は島を代表して、島の最大面積を求めて、4つの方向しか検索できません.
問題解
間は杭電の上で1本の類似の問題解をしたことがあって石油の面積を求めるので、これはそれより少し難しくて、最大の面積を要求して、深く捜索する応用
C++コード
class Solution {
public:

    int dfs(vector<vector<int>>& grid, int x0, int y0){
        int n, m, sum=1;
        n = grid.size();
        m = grid[0].size();

        grid[x0][y0] = 0; //       0,       
        int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};

        for(int i=0; i<4; i++){
            int x = x0 + dir[i][0];
            int y = y0 + dir[i][1];
            if(x>=0&&x=0&&y1)
                sum+=dfs(grid, x, y);
        }
        return sum;

    }
    int maxAreaOfIsland(vector<vector<int>>& grid) 
    {
        int mx = 0, n, m;
        n = grid.size();
        m = grid[0].size();
        for(int i=0; ifor(int j=0; jif(grid[i][j] == 1)   
                    mx = max(dfs(grid,i,j), mx);
            }
        return mx;
    }
};

pythonコード
class Solution(object):
    def dfs(self, grid, x0, y0):
        s = 1
        n = len(grid)
        m = len(grid[0])

        grid[x0][y0] = 0
        dire = [[0,1],[0,-1],[1,0],[-1,0]]
        for i in range(0,4):
            x = x0 + dire[i][0]
            y = y0 + dire[i][1]
            if x>=0 and xand y>=0 and yand grid[x][y] == 1:
                s = s + self.dfs(grid, x, y)
        return s


    def maxAreaOfIsland(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        mx = 0
        n = len(grid)
        m = len(grid[0])
        for i in range(0, n):
            for j in range(0, m):
                if grid[i][j] == 1:
                    mx = max(mx, self.dfs(grid, i,j))
        return mx