New Magic Square
Time limit2sMemory limit128 MB
Fill a 5x5 grid with numbers 1 to 25 so each row strictly increases, respecting up to one prefilled cell per row, and output the lexicographically smallest valid grid or -1.
- Level
Medium7 of 10
- Topics
- Backtracking, Greedy, Combinatorics, Matrix
- Solved
- No attempts yet
Problem
You must fill a 5 x 5 grid with the integers from 1 through 25, using each integer exactly once. In every row, the numbers must strictly increase from left to right.
Some cells may already contain numbers. In each row, at most one cell is already filled. Fill every remaining empty cell.
If the grid cannot be completed, print -1. If there are multiple valid completions, print the lexicographically smallest grid when read from top to bottom and, within each row, from left to right. In other words, minimize the value in row 1 column 1 first; if tied, minimize row 1 column 2, then row 1 column 3, and so on.
Input
Five lines are given. Each line contains five integers separated by spaces. An empty cell is given as 0. A nonzero value represents a cell that is already filled.
Output
Print the completed 5 x 5 grid in five lines. Each line must contain the five numbers in that row, separated by spaces.
If the grid cannot be completed, print -1.