200. The number of islands

200. The number of islands

Title Description

Given a two-dimensional grid by a '1' (land) and '0' (water) composition, the number of islands is calculated. An island surrounded by water, and it is through the horizontal or vertical direction is connected to each adjacent land. You can assume that the water surrounding the four sides of the grid are.

Example 1:

Enter:
11110
11010
11000
00000

Output: 1

Example 2:

Enter:
11000
11000
00100
00011

Output: 3

Code posted

class Solution {
    private int m,n;
    private int[][] direction = {{0,1},{0,-1},{1,0},{-1,0}};
    public int maxAreaOfIsland(int[][] grid) {
        if (grid == null || grid.length == 0){
            return 0;
        }
        m = grid.length;
        n = grid[0].length;
        int maxArea = 0;
        for (int i = 0; i < m; i ++){
            for (int j = 0; j < n; j ++){
                maxArea = Math.max(maxArea,dfs(grid,i,j));
            }
        }
        return maxArea;
    }
    private int dfs(int[][] grid, int r,int c){
        if (r < 0 || r >= m || c < 0 || c >= n || grid[r][c] ==0){
            return 0;
        }
        grid[r][c] = 0;
        int area = 1;
        for (int[] d : direction){
            area += dfs(grid,r + d[0],c + d[1]);
        }
        return area;
    }
}

Guess you like

Origin www.cnblogs.com/Tu9oh0st/p/10704533.html