Python undirected graph count connected components // 16-23 lines easy and clear solutions // 100 ms
23 lines 100 ms\n\nclass Solution:\n    def largestIsland(self, grid):\n        def explore(i, j):\n            dic[(i, j)], count[curr] = curr, count[curr] + 1
* 23 lines 100 ms\n```\nclass Solution:\n    def largestIsland(self, grid):\n        def explore(i, j):\n            dic[(i, j)], count[curr] = curr, count[curr] + 1\n            if i > 0 and grid[i - 1][j] == 1 and (i - 1, j) not in dic: explore(i - 1, j)\n            if j > 0 and grid[i][j - 1] == 1 and (i, j - 1) not in dic: explore(i, j - 1)\n            if i + 1 < len(grid) and grid[i + 1][j] ==1 and (i + 1, j) not in dic: explore(i + 1, j)\n            if j + 1 < len(grid) and grid[i][j + 1] == 1 and (i, j + 1) not in dic: explore(i, j + 1)\n        def neighbours(i, j, adj):\n            if i > 0 and grid[i - 1][j] == 1 and dic[(i - 1, j)] not in adj: adj.add(dic[(i - 1, j)])\n            if j > 0 and grid[i][j - 1] == 1 and dic[(i, j - 1)] not in adj: adj.add(dic[(i, j - 1)])\n            if i + 1 < len(grid) and grid[i + 1][j] ==1 and dic[(i + 1, j)] not in adj: adj.add(dic[(i + 1, j)])\n            if j + 1 < len(grid) and grid[i][j + 1] == 1 and dic[(i, j + 1)] not in adj: adj.add(dic[(i, j + 1)])\n            return adj\n        curr, dic, count, res = 0, {}, collections.defaultdict(int), 0\n        for i in range(len(grid)):\n            for j in range(len(grid)):\n                if grid[i][j] == 1 and (i, j) not in dic: curr += 1; explore(i, j)\n        for i in range(len(grid)):\n            for j in range(len(grid)):\n                if grid[i][j] == 1: res = max(res, count[dic[(i, j)]])\n                else: res = max(res, sum(count[r] for r in neighbours(i, j, set())) + 1)\n        return res\n```\n*  16 lines 150 ms\n```\nclass Solution:\n    def largestIsland(self, grid):\n        def proper(i, j): \n            return (c for c in ((i-1,j),(i+1,j),(i,j-1),(i,j+1)) if 0<=c[0]<len(grid) and 0<=c[1]<len(grid) and grid[c[0]][c[1]]==1)\n        def explore(i, j):\n            dic[(i, j)], count[curr] = curr, count[curr] + 1   \n            for cp in proper(i, j):\n                if cp not in dic: explore(cp[0], cp[1])\n        curr, dic, count, res = 0, {}, collections.defaultdict(int), 0\n        for i in range(len(grid)):\n            for j in range(len(grid)):\n                if grid[i][j] == 1 and (i, j) not in dic: curr += 1; explore(i, j)\n        for i in range(len(grid)):\n            for j in range(len(grid)):\n                if grid[i][j] == 1: res = max(res, count[dic[(i, j)]])\n                else: res = max(res, sum(count[r] for r in {dic[c] for c in proper(i, j)}) + 1)\n        return res\n```
[]