Skip to content

Latest commit

 

History

History
50 lines (44 loc) · 1.3 KB

695.岛屿的最大面积.md

File metadata and controls

50 lines (44 loc) · 1.3 KB

方法一:DFS

class Solution {
    int res = 0;
    int curArea = 0;
    public int maxAreaOfIsland(int[][] grid) {
        int rows = grid.length;
        if (rows == 0) return res;
        int cols = grid[0].length;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (grid[i][j] == 1) {
                    curArea = 0;
                    dfs(grid, i, j);
                }
            }
        }
        return res;
    }

    public void dfs(int[][] grid, int row, int col) {
        if (!inArea(grid, row, col)) return ;
        if (grid[row][col] == 2 || grid[row][col] == 0) return;
        grid[row][col] = 2;
        res = Math.max(res, ++curArea);
        dfs(grid, row - 1, col);
        dfs(grid, row + 1, col);
        dfs(grid, row, col - 1);
        dfs(grid, row, col + 1);
    }

    public boolean inArea(int[][] grid, int row, int col) {
        return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length;
    }
}

岛屿都需要上下左右进行搜索,除了可以像上面这种分别写上下左右搜索外,还可以用数组

int[] x = new int[]{0, 0, -1, 1};
int[] y = new int[]{-1, 1, 0, 0};
for (int i = 0; i < 4; i++) {
    int nextRow = row + x[i];
    int nextCol = col + y[i];
    dfs(grid,)
}