2192. All Ancestors of a Node in a Directed Acyclic Graph
Medium
You are given a positive integer n representing the number of nodes of a Directed Acyclic Graph (DAG). The nodes are numbered from 0 to n - 1 (inclusive).
You are also given a 2D integer array edges, where edges[i] = [fromi, toi] denotes that there is a unidirectional edge from fromi to toi in the graph.
Return a list answer, where answer[i] is the list of ancestors of the ith node, sorted in ascending order.
A node u is an ancestor of another node v if u can reach v via a set of edges.
Example 1:
Example 2:
Constraints:
Solution:
class Solution { /** * @param Integer $n * @param Integer[][] $edges * @return Integer[][] */ function getAncestors($n, $edges) { $adjacencyList = array_fill(0, $n, []); foreach ($edges as $edge) { $from = $edge[0]; $to = $edge[1]; $adjacencyList[$to][] = $from; } $ancestorsList = []; for ($i = 0; $i < $n; $i++) { $ancestors = []; $visited = []; $this->findChildren($i, $adjacencyList, $visited); for ($node = 0; $node < $n; $node++) { if ($node == $i) continue; if (in_array($node, $visited)) $ancestors[] = $node; } $ancestorsList[] = $ancestors; } return $ancestorsList; } private function findChildren($currentNode, &$adjacencyList, &$visitedNodes) { $visitedNodes[] = $currentNode; foreach ($adjacencyList[$currentNode] as $neighbour) { if (!in_array($neighbour, $visitedNodes)) { $this->findChildren($neighbour, $adjacencyList, $visitedNodes); } } } }Contact Links
The above is the detailed content of All Ancestors of a Node in a Directed Acyclic Graph. For more information, please follow other related articles on the PHP Chinese website!