class MNode: Hashable, Equatable {var code: Intvar mappedstats = [Int:Int]() var con = Set<MNode>()init(code: Int) {self.code = code}static func == (lhs: MNode, rhs: MNode) -> Bool {return lhs.code == rhs.code}func hash(into hasher: inout Hasher) {hasher.combine(code)}
}
extension Daily {static func test_leetcode815() {var routes = [[Int]]()var idx = 0while idx < 9000 {var sublist = [Int]()var sidx = 0while sidx < 301 {sublist.append(idx)sidx += 1idx += 1}routes.append(sublist)idx -= 1}let source = 0, target = 90000 for sublist in routes {print(sublist)}let start = NSDate.nowprint("开始时间 \(NSDate.now)")let res = Daily.leetcode815(routes, source, target)let end = NSDate.nowprint("输出:\(res), 耗时 \(end.timeIntervalSince(start))\n")}static func leetcode815(_ routes: [[Int]], _ source: Int, _ target: Int) -> Int {if source == target {return 0}var net = [MNode]()var contain = [MNode]()for idx in 0..<routes.count {let item = routes[idx]let node = MNode(code: idx)for astation in item {node.mappedstats[astation] = 1}net.append(node)if node.mappedstats[source] == 1 {contain.append(node)}}var slmap = [Int:[Int]]()for node in net {let sts = node.mappedstats.keysfor station in sts {if slmap[station] == nil {slmap[station] = [node.code]}else {slmap[station]!.append(node.code) }}}for (_, list) in slmap {if list.count < 2 {continue}for idx in list {for subidx in list {if subidx != idx {net[idx].con.insert(net[subidx])}}}}let RMAX = net.count + 11 var minroute = RMAXfor sidx in 0..<contain.count {let node = contain[sidx]if node.mappedstats[target] == 1 {minroute = 0break}var map = [Int](repeating: RMAX, count: net.count)map[node.code] = 0var minnodes = [MNode]()for cnode in node.con {map[cnode.code] = 1}minnodes.append(contentsOf: node.con)var arrDone = [Int](repeating: 0, count: net.count)arrDone[node.code] = 1while minnodes.count > 0 {let minnode = minnodes.removeFirst() arrDone[minnode.code] = 1let steps = map[minnode.code]for cnode in minnode.con {if arrDone[cnode.code] == 0 && map[cnode.code] > steps + 1 {map[cnode.code] = steps + 1minnodes.append(cnode)}}if minnode.mappedstats[target] == 1 {if map[minnode.code] < minroute {minroute = map[minnode.code]}break}}
}for item in net {item.con.removeAll()}return minroute == RMAX ? -1 : minroute + 1}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!