LeetCode_Study_Plan/Algorithm

695. Max Area of Island java

개발하는루루 2022. 12. 22. 21:39

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

 

Max Area of Island - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

class Solution {
    int m;
    int n;
    boolean[][] visited;
    int[][] grid;
    int cnt = 0;

    public int maxAreaOfIsland(int[][] grid) {
        this.m = grid.length;
        this.n = grid[0].length;
        this.visited = new boolean[this.m][this.n];
        this.grid = grid;
        int max_num = 0;

        for (int i = 0; i < this.m; i++) {
            for (int j = 0; j < this.n; j++) {
                if (!visited[i][j] && this.grid[i][j] == 1) {
                    this.cnt = 0;
                    dfs(i, j);
                    max_num = Math.max(max_num, this.cnt);
                }
            }
        }

        return max_num;
    }

    private void dfs(int i, int j) {
        if (go_outside(i, j)) return;
        if (this.visited[i][j] || this.grid[i][j] == 0) return;
        this.visited[i][j] = true;
//        System.out.println("i: " + i + " j: " + j);
        this.cnt++;
        dfs(i+1, j);
        dfs(i, j+1);
        dfs(i-1, j);
        dfs(i, j-1);
    }

    private boolean go_outside(int i, int j) {
        if (i < 0 || i >= this.m || j < 0 || j >= this.n) {
            return true;
        }
        return false;
    }
}