程式語言 - LeetCode - C++ - 695. Max Area of Island



題目:


解答:

class Solution {
public:
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        vector<vector<bool>> visited(m, vector<bool>(n, false));
        vector<pair<int, int>> dir = {
            { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 }
        };

        auto dfs = [&](this auto&& dfs, int x, int y) -> int {
            if (x < 0 || x >= m || y < 0 || y >= n || !grid[x][y] || visited[x][y]) {
                return 0;
            }

            int ans = 1;

            visited[x][y] = true;

            for (auto [dx, dy] : dir) {
                int nx = x + dx;
                int ny = y + dy;

                if (nx < 0 || nx >= m || ny < 0 || ny >= n || !grid[nx][ny] || visited[nx][ny]) {
                    continue;
                }

                ans += dfs(nx, ny);
            }

            return ans;
        };

        int ans = 0;

        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (visited[i][j] == false) {
                    ans = max(ans, dfs(i, j));
                }
            }
        }

        return ans;
    }
};