Depth-first search template

Depth-first search template

Typical examples and program examples

A typical example is 695. The maximum area of ​​the island The
sample code is as follows

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;
}

to sum up

In fact, many dfs problems can be solved with the same routines in the dfs search part, so here is a brief summary record
1. First, come up with an if to judge the legitimacy, filter out the cases that do not meet the conditions, and the legitimacy judgment here Generally, it is necessary to judge whether it has been visited. In fact, it is to filter out the illegal and visited elements in the neighborhood
2. Next mark the current element has been visited
3. The domain search is recursive, and the business calculation is performed at the same time

Guess you like

Origin www.cnblogs.com/wunsiang/p/12717839.html