LeetCode695. 島嶼的最大面積

LeetCode695. 島嶼的最大面積

給定一個包含了一些 0 和 1的非空二維數組 grid , 一個 島嶼 是由四個方向 (水平或垂直) 的 1 (代表土地) 構成的組合。你可以假設二維矩陣的四個邊緣都被水包圍着。
找到給定的二維數組中最大的島嶼面積。(如果沒有島嶼,則返回面積爲0。)

示例 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]]
對於上面這個給定矩陣應返回 6。注意答案不應該是11,因爲島嶼只能包含水平或垂直的四個方向的‘1’。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/max-area-of-island

思路分析:基於回溯法思路

1、max 記錄最大島嶼面積

2、visited[][] 記錄當前座標是否已被訪問

3、當遍歷一個未被訪問過的 1 時,向上下左右進行遍歷,每遍歷一個 1島嶼面積+1

class Solution {
    int[][] move = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
    public int maxAreaOfIsland(int[][] grid) {
        int max = 0; // 記錄最大島嶼面積
        boolean[][] visited = new boolean[grid.length][grid[0].length]; // 記錄當前座標是否已被訪問
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) { // 
                    int count = DFS(grid, visited, i, j, 0);
                    max = max > count ? max : count;
                }
            }
        }
        return max;
    }

    private int DFS(int[][] grid,boolean[][] visited,int x,int y,int count) {
        if (!valid(grid, visited, x, y)) {
            return count;
        }
        visited[x][y] = true;
        for (int i = 0; i < move.length; i++) { // 上下左右進行遍歷
            count = DFS(grid, visited, x + move[i][0], y + move[i][1], count);
        }
        return count+1; // 更新島嶼面積
    }

    private boolean valid(int[][] grid,boolean[][] visited,int x,int y){
        if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || visited[x][y] || grid[x][y] != 1) { // 驗證合法性,未越界且未被訪問值爲 1
            return false;
        }
        return true;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章