Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Build a Matrix With Conditions

XPChallenge Points: 30
levelLevel: Hard

You are given a positive number k. You must place every integer from 1 to k exactly one time into a k x k grid. All other cells should contain 0.

Additionally, you are given two lists of constraints:

  • rowConditions: Each pair [a, b] indicates that a must be located in a row strictly above b.

  • colConditions: Each pair [x, y] indicates that x must be located in a column strictly to the left of y.

You must return any matrix that satisfies both all row ordering and column ordering relations.
If it is impossible to satisfy all constraints simultaneously (i.e., the constraints conflict), return an empty matrix.

Example 1:

Input: k = 4 rowConditions = [[1,3], [2,4]] colConditions = [[3,2], [1,4]]

Output: [ [1,0,0,0], [0,3,0,2], [0,0,4,0], [0,0,0,0] ]

Explanation:

1 is placed in a row above 3 2 is above 4 3 is positioned to the left of 2 1 is to the left of 4 All constraints hold true.

Example 2:

Input: k = 3 rowConditions = [[1,2],[2,3],[3,1]] colConditions = [[1,3]]

Output: []

Explanation:

The row constraints form a cycle: 1 > 2 > 3 > 1, making them impossible to satisfy.

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result