For each starting country \(s\), the set of destination countries which it's possible to reach must form some consecutive interval \(A_s..B_s\), such that \(A_s \leq s \leq B_s\). We can begin by assuming that \(B_s = s\), and then repeatedly increase \(B_s\) until it has reached either country \(N\) or the first country after \(s\) which is unreachable from it. As long as \(B_s < N\), it should be incremented if flights are allowed from country \(B_s\) to country \(B_s+1\), which is the case if and only if \(O_{B_s} = I_{B_s+1} =\) *"Y"*. The above process can be performed for each starting country \(s\), and repeated similarly to compute each \(A_s\) value. \(A_{1..N}\) and \(B_{1..N}\) may then be used to populate the required \(P\) matrix. Each part of this solution takes \(O(N^2)\) time.