C++ with DFS


  • 0
    S
    class Solution {
    public:
        int countSum(int i, int j, vector<vector<int>>& grid) {
            if (i < 0 || i >= grid.size() || j < 0 || j >= grid[i].size() || grid[i][j] == 0) {
                return 0;
            }
            int currentSum = 1;
            grid[i][j] = 0;
            currentSum += countSum(i - 1, j, grid);
            currentSum += countSum(i + 1, j, grid);
            currentSum += countSum(i, j - 1, grid);
            currentSum += countSum(i, j + 1, grid);
            return currentSum;
        }
        
        int maxAreaOfIsland(vector<vector<int>>& grid) {
            int max = 0;
            for (int i = 0; i < grid.size(); i++) {
                for (int j = 0; j < grid[i].size(); j++) {
                    int sum = countSum(i, j, grid);
                    max = (sum > max) ? sum : max;
                }
            }
            return max;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.