695. 岛屿的最大面积

floodfill算法(DFS+回溯)

class Solution {

    int m;
    int n;
    boolean[][] used;
    int[][] move = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

    public int maxAreaOfIsland(int[][] grid) {

        m = grid.length;
        n = grid[0].length;
        int max = 0;

        used = new boolean[m][n];

        for (int i = 0; i < m; i++) {

            for (int j = 0; j < n; j++) {

                if (grid[i][j] == 1 && !used[i][j]) {
                    max = Math.max(max, dfs(grid, i, j));
                }
            }
        }

        return max;
    }

    public int dfs(int[][] grid, int row, int col) {

        /**
         * 每次搜索时,当前元素肯定符合条件,sum初始值为1
         */
        used[row][col] = true;
        int sum = 1;

        for (int i = 0; i < 4; i++) {

            int newRow = row + move[i][0];
            int newCol = col + move[i][1];

            if (newRow >=0 && newRow < m && newCol >= 0 && newCol < n && grid[newRow][newCol] == 1 && !used[newRow][newCol]) {
                sum += dfs(grid, newRow, newCol);
            }
        }

        return sum;
    }
}

/**
 * 时间复杂度 O(m×n)
 * 空间复杂度 O(m×n)
 */

https://leetcode-cn.com/problems/max-area-of-island/

上一篇:463. 岛屿的周长


下一篇:力扣每日一题(九)