C++ dfs solution
\n\nThis solution can be further optimised.\n# Approach\n Describe your approach to solving the problem. \nI tried to give a distinct code for each island and s
\n\nThis solution can be further optimised.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nI tried to give a distinct code for each island and store it in the map( we use dfs for that ) \nthen for edge cases\n1)no islands are present \n2)only one island is present\nthen we iterate through the grid and if we find water (grid[i][j]==0)this code then checks 4 directions of water and pushes the grid values in the set (for distinct). then we add the (collective area+1)(as we turn the 0 to 1 ) and we update the max area.\n\n\n# Code\n```\n\n\nclass Solution {\npublic:\n    void dfs(int c, int i, int j, int& ans, vector<vector<int>>& visit,\n             vector<vector<int>>& grid) {\n        int n = grid.size();\n        visit[i][j] = 1;\n        grid[i][j] = c;\n        ans++;\n        vector<int> d = {-1, 0, 1, 0, -1};\n        for (int k = 0; k < 4; k++) {\n            int x = i + d[k];\n            int y = j + d[k + 1];\n            if (x >= 0 && y >= 0 && y < n && x < n && grid[x][y] == 1 &&\n                visit[x][y] == 0) {\n                dfs(c, x, y, ans, visit, grid);\n            }\n        }\n    }\n    int largestIsland(vector<vector<int>>& grid) {\n        int n = grid.size();\n        vector<int> d = {-1, 0, 1, 0, -1};\n        vector<vector<int>> visit(n, vector<int>(n, 0));\n        map<int, int> mpp;\n        int c = 1, ma = 0;\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < n; j++) {\n                if (grid[i][j] > 0 && visit[i][j] == 0) {\n                    int ans = 0;\n                    dfs(c, i, j, ans, visit, grid);\n                    mpp[c] = ans;\n                    ma = max(ma, ans);\n                    c++;\n                }\n            }\n        }\n        if (c == 1)\n            return 1;\n        if (c == 2) {\n            int ans = mpp[1];\n            ans++;\n            if (ans >= n * n)\n                return n * n;\n            return ans;\n        }\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < n; j++) {\n                if (grid[i][j] == 0) {\n                    int area = 0;\n                    unordered_set<int> set;\n                    for (int k = 0; k < 4; k++) {\n                        int x = i + d[k];\n                        int y = j + d[k + 1];\n                        if (x >= 0 && y >= 0 && y < n && x < n &&\n                            grid[x][y] > 0) {\n                            set.insert(grid[x][y]);\n                        }\n                    }\n                    for (auto it : set) {\n                        area += mpp[it];\n                    }\n                    ma = max(ma, area + 1);\n                }\n            }\n        }\n        return ma;\n    }\n};\n```
['C++']