A universal sink in a directed graph is a vertex with in-degree |V|-1 and out-degree 0. Given an adjacency matrix representation, we can determine the existence of such a vertex in O(V) time by simultaneously traversing rows and columns.
func findUniversalSink(matrix [][]int) int {
n := len(matrix)
candidate := 0
for i := 0; i < n; i++ {
if matrix[candidate][i] == 1 {
candidate = i
}
}
for j := 0; j < n; j++ {
if j != candidate && (matrix[candidate][j] == 1 || matrix[j][candidate] == 0) {
return -1
}
}
return candidate
}
This algorithm works by first identifying a cendidate vertex that might be the universal sink. It then verifies whether this candidate meets both conditions: zero out-degree (all entries in its row are 0) and maximum in-degree (all other vertices have edges pointing to it).
The time complexity is O(V) because we traverse at most 2V elements: first to find the caniddate (V comparisons) and then to validate it (V checks).