Leetcode 695 Solution

This article provides solution to leetcode question 695 (max-area-of-island)

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

Solution

class Solution {
public:
    int maxArea(vector<vector<int>>& grid, int i, int j, int m, int n, vector<vector<bool>>& visited)
    {
        if (grid[i][j] == 0 || visited[i][j])
            return 0;

        visited[i][j] = true;

        int area = 1;

        if (i > 0)
            area += maxArea(grid, i - 1, j, m, n, visited);

        if (i < m - 1)
            area += maxArea(grid, i + 1, j, m, n, visited);

        if (j > 0)
            area += maxArea(grid, i, j - 1, m, n, visited);

        if (j < n - 1)
            area += maxArea(grid, i, j + 1, m, n, visited);

        return area;
    }

    int maxAreaOfIsland(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();

        vector<vector<bool>> visited(m, vector<bool>(n, false));

        int max_island_size = 0;

        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (grid[i][j] == 0 || visited[i][j])
                    continue;

                int island_size = maxArea(grid, i, j, m, n, visited);
                max_island_size = max(island_size, max_island_size);
            }
        }

        return max_island_size;
    }
};