The transitive closure of a relation adds a pair (a, c) whenever you can get from a to c through a chain of related elements. It is the "reachable" relation of a network. Your program computes it with Warshall's algorithm.
What to build
A program that prints the matrix of the transitive closure of a relation.
Requirements
- Read n and m, then m pairs a b, as in the matrix exercise.
- Add the pair (a, c) whenever there is a chain a to b to ... to c in the given pairs. A pair (a, a) is added only if a is on a cycle.
- Print the matrix of the closure: n lines of n values 0 or 1 separated by spaces.
Input
The first line has n and m. Each of the next m lines has one pair.
Output
n lines.
Constraints
1 ≤ n ≤ 8; 0 ≤ m ≤ 30.
Example
Input:
3 2
1 2
2 3
Output:
0 1 1
0 0 1
0 0 0
Why it works
Allowing the elements 1 to k as stopovers, a path from i to j either avoids k or goes i to k and then k to j. Warshall's three loops apply that rule for k = 1, 2, ..., n, so after the last round every path through any stopovers has been added, and nothing else.
Examples
3 2 1 2 2 3
0 1 1 0 0 1 0 0 0
4 3 1 2 2 3 3 1
1 1 1 0 1 1 1 0 1 1 1 0 0 0 0 0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Warshall's algorithm: for each k, for each i, for each j, set reach[i][j] to reach[i][j] or (reach[i][k] and reach[k][j]).
Hint 2
The loop over k must be the outermost one.
Hint 3
Print the matrix as in the easy exercise: n lines of 0 and 1.
Solution
Show one correct solution (try it yourself first)
n, m = map(int, input().split())
reach = [[0] * n for _ in range(n)]
for _ in range(m):
a, b = map(int, input().split())
reach[a - 1][b - 1] = 1
for k in range(n):
for i in range(n):
for j in range(n):
if reach[i][k] and reach[k][j]:
reach[i][j] = 1
for row in reach:
print(*row)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step