A relation on the numbers 1 to n can be drawn as a matrix with a 1 in row a and column b when (a, b) is in the relation. Your program builds that matrix from a list of pairs.
What to build
A program that prints the 0/1 matrix of a relation.
Requirements
- Read n and m, then m pairs a b, each meaning that a is related to b.
- Print n lines of n values 0 or 1 separated by spaces: the value in row a, column b is 1 exactly when the pair a b was given.
Input
The first line has n and m. Each of the next m lines has one pair.
Output
n lines.
Constraints
1 ≤ n ≤ 10; 0 ≤ m ≤ 30.
Example
Input:
3 2
1 2
2 3
Output:
0 1 0
0 0 1
0 0 0
Why it works
A relation on A is a subset of A × A, so each pair either belongs to it or not, and a matrix shows that choice cell by cell. Reading the matrix back gives the same pairs, and a repeated pair simply sets the same cell again.
Examples
3 2 1 2 2 3
0 1 0 0 0 1 0 0 0
2 3 1 1 1 2 2 2
1 1 0 1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Start with an n by n table of zeros.
Hint 2
For each pair (a, b) set the cell in row a and column b to 1; the pairs are numbered from 1.
Hint 3
Print each row with spaces between the values.
Solution
Show one correct solution (try it yourself first)
n, m = map(int, input().split())
M = [[0] * n for _ in range(n)]
for _ in range(m):
a, b = map(int, input().split())
M[a - 1][b - 1] = 1
for row in M:
print(*row)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step