在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ In a 2D grid of After, what is the size of the largest island? (An island is a 4-directionally connected group of Example 1: Input: [[1, 0], [0, 1]] Output: 3 Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3. Example 2: Input: [[1, 1], [1, 0]] Output: 4 Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4. Example 3: Input: [[1, 1], [1, 1]] Output: 4 Explanation: Can't change any 0 to 1, only one island with area = 4. Notes:
在二维地图上, 进行填海之后,地图上最大的岛屿面积是多少?(上、下、左、右四个方向相连的 示例 1: 输入: [[1, 0], [0, 1]] 输出: 3 解释: 将一格0变成1,最终连通两个小岛得到面积为 3 的岛屿。 示例 2: 输入: [[1, 1], [1, 0]] 输出: 4 解释: 将一格0变成1,岛屿的面积扩大为 4。 示例 3: 输入: [[1, 1], [1, 1]] 输出: 4 解释: 没有0可以让我们变成1,面积依然为 4。 说明:
Runtime: 104 ms
Memory Usage: 19.9 MB
1 class Solution { 2 var N:Int = 0 3 func largestIsland(_ grid: [[Int]]) -> Int { 4 var grid = grid 5 N = grid.count 6 var index:Int = 3 7 var res:Int = 0 8 var area:[Int:Int] = [Int:Int]() 9 for x in 0..<N 10 { 11 for y in 0..<N 12 { 13 if grid[x][y] == 1 14 { 15 area[index] = dfs(&grid, x, y, index) 16 res = max(res, area[index,default:0]) 17 index += 1 18 } 19 } 20 } 21 for x in 0..<N 22 { 23 for y in 0..<N 24 { 25 if grid[x][y] == 0 26 { 27 var seen:Set<Int> = Set<Int>() 28 var cur:Int = 1 29 for (key,val) in move(x, y) 30 { 31 index = grid[key][val] 32 if index > 1 && !seen.contains(index) 33 { 34 seen.insert(index) 35 cur += area[index,default:0] 36 } 37 } 38 res = max(res, cur) 39 } 40 } 41 } 42 return res 43 } 44 45 func move(_ x:Int,_ y:Int) -> [(Int,Int)] 46 { 47 var res:[(Int,Int)] = [(Int,Int)]() 48 if valid(x, y + 1) {res.append((x, y + 1))} 49 if valid(x, y - 1) {res.append((x, y - 1))} 50 if valid(x + 1, y) {res.append((x + 1, y))} 51 if valid(x - 1, y) {res.append((x - 1, y))} 52 return res 53 } 54 55 func valid(_ x:Int,_ y:Int) -> Bool 56 { 57 return 0 <= x && x < N && 0 <= y && y < N 58 } 59 60 func dfs(_ grid:inout [[Int]],_ x:Int,_ y:Int,_ index:Int) -> Int 61 { 62 var area:Int = 0 63 grid[x][y] = index 64 for (key,val) in move(x, y) 65 { 66 if grid[key][val] == 1 67 { 68 area += dfs(&grid, key, val, index) 69 } 70 } 71 return area + 1 72 } 73 }
|
请发表评论