The maximum area of the communication component -DFS- disjoint-set island -695 - FIG.

2020-03-15 16:41:45

Problem Description:

Given a two-dimensional array of non-null grid number 0 and 1, is an island formed of a combination of four directions (horizontal or vertical) 1 (representing the land). You can assume that the four edges of the two-dimensional matrix are surrounded by water.

Find a given two-dimensional array in the largest island in the area. (If there are no islands, the area is returned to 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]]
for the above should return the given matrix 6. Note that the answer should not be 11, since the islands comprise only four horizontal or vertical direction is '1'.

Example 2:

[[0,0,0,0,0,0,0,0]]
For the above given matrix, 0 is returned.

note: 

A given length and width of no more than 50 grid matrix.

Similar problems:

749. isolate virus

803. Arkanoid

Problem Solving:

A solution: DFS

Solving use DFS to be understood that the connected components of staining the entire figure, the number of patches in the current recording dyed in the dyeing process, can last maximum value.

Time complexity: O (mn)

    int[][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    int color = 1;
    int area = 0;
    int res = 0;
    public int maxAreaOfIsland(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    area = 0;
                    dfs(grid, i, j, ++color);
                    res = Math.max(res, area);
                }
            }
        }
        return res;
    }
    
    private void dfs(int[][] grid, int x, int y, int color) {
        int m = grid.length;
        int n = grid[0].length;
        grid[x][y] = color;
        area += 1;
        for (int[] dir : dirs) {
            int nx = x + dir[0];
            int ny = y + dir[1];
            if (nx < 0 || nx >= m || ny < 0 || ny >= n || grid[nx][ny] != 1) continue;
            dfs(grid, nx, ny, color);
        }
    }

 

Solution two: disjoint-set

 

Guess you like

Origin www.cnblogs.com/hyserendipity/p/12498427.html