leetcode 695 岛屿的最大面积

思路: 就是运用DFS深搜    

           先定义方向  

          然后定义dfs 递归函数,判断何时继续走,何时中止

          然后在主函数循环遍历地图调用 dfs

class Solution {
    int [][]direction = {
    {0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    public int maxAreaOfIsland(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        
        int max = 0;
        for(int i =0; i < m;  i ++)
        {
            for(int j = 0; j< n; j++)
            {
                max = Math.max(max, dfs(i, j,grid, direction, m , n));

            }
        }
        return max ;
    }

    public int dfs(int r , int c , int[][] grid,int[][] direction, int m , int n)
    {
        if(r < 0|| c < 0 || r >= m || c >= n || grid[r][c] == 0)
        {
            return 0;
        }

        grid[r][c] = 0;//走过的点置为0
        int area = 1;
        for(int []d :direction)
        {
            area += dfs(r+d[0], c+d[1],grid, direction, m, n);
        }
        return area;
    }
}

 

你可能感兴趣的:(leetcode 695 岛屿的最大面积)