我有一个自定义对象 (MyObject
) 数组 (myArray
)。数组中的每个对象都连接到数组中的至少一个其他对象(参见下面的代码)。 我正在尝试找到一种方法来确定 myArray
中的所有对象是否都相互连接。
class MyObject {
var id: Int = 0
var connectedIds: [Int] = []
}
如果 myArray
包含 5 个元素 (A
, B
, C
, D
, E
; A.id
= 0, B.id
= 1, ...), 我想判断这五个是不是以某种方式连接。每个对象都有一个名为 connectedIds
的数组,其中包含它连接到的对象的 id
(不包括它自己)。
例如,这将是有效的:
print(A.connectedIds) // [1]
print(B.connectedIds) // [0, 2]
print(C.connectedIds) // [1, 4]
print(D.connectedIds) // [4]
print(E.connectedIds) // [2, 3]
...但这不会:
print(A.connectedIds) // [1]
print(B.connectedIds) // [0]
print(C.connectedIds) // [3, 4]
print(D.connectedIds) // [2, 4]
print(E.connectedIds) // [2, 3]
最佳答案
算法基于找到两点之间的路线,另一个检查是否所有点都可以连接(它们之间有路线):
// Find route from an object to other object
func findNewRoute(currentRoute: inout [Int], from: Int, to: Int) {
currentRoute.append(from)
let connectedObjects = (objects.filter { $0.id == from }.first!).connectedIds
for index in connectedObjects {
if !currentRoute.contains(index) {
findNewRoute(currentRoute: ¤tRoute, from: index, to: to)
}
}
}
// Check Validation
func checkValid(group: [MyObject]) -> Bool {
for object in objects {
if !(objects.filter {
element in
var result:[Int] = []
findNewRoute(currentRoute: &result, from: object.id, to: element.id)
return !result.contains(element.id)
}).isEmpty {
return false
}
}
return true
}
关于arrays - 如何确定数组中的所有对象是否在 Swift 中连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54879458/