You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<p>We create a 2D array $f$, where $f[i][j]$ indicates whether node $i$ can reach node $j$.</p>
77744
+
<p>Next, we iterate through the prerequisites array $prerequisites$. For each item $[a, b]$ in it, we set $f[a][b]$ to $true$.</p>
77745
+
<p>Then, we use Floyd's algorithm to compute the reachability between all pairs of nodes.</p>
77746
+
<p>Specifically, we use three nested loops: first enumerating the intermediate node $k$, then the starting node $i$, and finally the ending node $j$. For each iteration, if node $i$ can reach node $k$ and node $k$ can reach node $j$, then node $i$ can also reach node $j$, and we set $f[i][j]$ to $true$.</p>
77747
+
<p>After computing the reachability between all pairs of nodes, for each query $[a, b]$, we can directly return $f[a][b]$.</p>
77748
+
<p>The time complexity is $O(n^3)$, and the space complexity is $O(n^2)$, where $n$ is the number of nodes.</p>
<p>Similar to Solution 1, we create a 2D array $f$, where $f[i][j]$ indicates whether node $i$ can reach node $j$. Additionally, we create an adjacency list $g$, where $g[i]$ represents all successor nodes of node $i$, and an array $indeg$, where $indeg[i]$ represents the in-degree of node $i$.</p>
77943
+
<p>Next, we iterate through the prerequisites array $prerequisites$. For each item $[a, b]$ in it, we update the adjacency list $g$ and the in-degree array $indeg$.</p>
77944
+
<p>Then, we use topological sorting to compute the reachability between all pairs of nodes.</p>
77945
+
<p>We define a queue $q$, initially adding all nodes with an in-degree of $0$ to the queue. Then, we continuously perform the following operations: remove the front node $i$ from the queue, then iterate through all nodes $j$ in $g[i]$, setting $f[i][j]$ to $true$. Next, we enumerate node $h$, and if $f[h][i]$ is $true$, we also set $f[h][j]$ to $true$. After this, we decrease the in-degree of $j$ by $1$. If the in-degree of $j$ becomes $0$, we add $j$ to the queue.</p>
77946
+
<p>After computing the reachability between all pairs of nodes, for each query $[a, b]$, we can directly return $f[a][b]$.</p>
77947
+
<p>The time complexity is $O(n^3)$, and the space complexity is $O(n^2)$, where $n$ is the number of nodes.</p>
0 commit comments