[Swift]LeetCode1162. 地图分析 | As Far from Land as Possible
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an N x N? The distance used in this problem is the?Manhattan distance:?the distance between two cells? If no land or water exists in the grid,return? Example 1: Input: [[1,1],[0,0],[1,1]]
Output: 2 Explanation: The cell (1,1) is as far as possible from all the land with distance 2.
Example 2: Input: [[1,0]]
Output: 4 Explanation: The cell (2,2) is as far as possible from all the land with distance 4.
Note:
你现在手里有一份大小为?N x N 的『地图』(网格)? 我们这里说的距离是『曼哈顿距离』(?Manhattan Distance): 如果我们的地图上只有陆地或者海洋,请返回? 示例 1: 输入:[[1,1]] 输出:2 解释: 海洋区域 (1,1) 和所有陆地区域之间的距离都达到最大,最大距离为 2。 示例 2: 输入:[[1,0]] 输出:4 解释: 海洋区域 (2,2) 和所有陆地区域之间的距离都达到最大,最大距离为 4。 提示:
Runtime:?828 ms
Memory Usage:?21 MB
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public var val: Int 5 * public var left: TreeNode? 6 * public var right: TreeNode? 7 * public init(_ val: Int) { 8 * self.val = val 9 * self.left = nil 10 * self.right = nil 11 * } 12 * } 13 */ 14 class Solution { 15 var s:[Int:Int] = [Int:Int]() 16 func maxLevelSum(_ root: TreeNode?) -> Int { 17 dfs(root,1) 18 var best:Int = s[1,default:0] 19 var v:Int = 1 20 for (key,val) in s 21 { 22 if val > best 23 { 24 best = val 25 v = key 26 } 27 } 28 return v 29 } 30 31 func dfs(_ root: TreeNode?,_ level:Int) 32 { 33 if root == nil {return} 34 dfs(root!.left,level + 1) 35 dfs(root!.right,level + 1) 36 s[level,default:0] += root!.val 37 } 38 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |