695. 岛屿的最大面积
递归解法
执行用时:3 ms, 在所有 Java 提交中击败了72.95% 的用户 内存消耗:38.8 MB, 在所有 Java 提交中击败了84.91% 的用户
class Solution {// 存储是否遍历过private boolean[][] gridTemp;// 存储当前岛屿面积private int count;// 定义上下左右方向private int[][] dire = new int[][]{new int[]{0, 1},new int[]{0, -1},new int[]{1, 0},new int[]{-1, 0}};public int maxAreaOfIsland(int[][] grid) {int rowCount = grid.length;int colCount = grid[0].length;gridTemp = new boolean[rowCount][colCount];int max = 0;for (int i = 0; i < rowCount; i++) {for (int j = 0; j < colCount; j++) {if (!gridTemp[i][j]) {count = 0;calculateAreaRecursion(grid, i, j);max = Math.max(count, max);}}}return max;}public void calculateAreaRecursion(int[][] grid, int x, int y) {// 判断坐标是是否越界if (!(x >= 0 && x < grid.length && y >= 0 && y < grid[0].length)) return;// 如果遍历过,返回if (gridTemp[x][y]) return;// 将当前坐标更新为已遍历gridTemp[x][y] = true;// 如果当前是岛屿,面积加一,if (grid[x][y] == 1) {count++;// 递归遍历上下左右节点for (int[] d : dire) {calculateAreaRecursion(grid, x + d[0], y + d[1]);}}}}
