clueless coding // TODO: be smarter

LeetCode Max Area of Island: CPP Solution



TL;DR Code Solution


int maxAreaOfIsland(vector<vector<int>>& grid) {

    int result = 0;

    for (int i = 0; i < grid.size(); i++) {
        for (int j = 0; j < grid[0].size(); j++) {
            if (grid[i][j] == 1) {
                result = max(result, helper(grid, i, j));    
            }
        }
    }

    return result;


}

int helper(vector<vector<int>>& grid, int i, int j) {
    queue<pair<int, int>> que;
    que.push(make_pair(i, j));

    int total = 0;
    while (!que.empty()) {
        pair<int, int> cur = que.front();
        que.pop();

        if (cur.first < 0 || cur.first >= grid.size() || cur.second < 0 || 
            cur.second >= grid[0].size() || 
            grid[cur.first][cur.second] == 0) {
            continue;
        }
        else {
            total++;
            grid[cur.first][cur.second] = 0;
            que.push(make_pair(cur.first + 1, cur.second));
            que.push(make_pair(cur.first - 1, cur.second));
            que.push(make_pair(cur.first, cur.second + 1));
            que.push(make_pair(cur.first, cur.second - 1));
        }
    }

    return total;

}