We need to determine for which n we can construct an n x n matrix containing numbers 1..n^2 exactly once, such that adjacent cells (sharing a side) contain numbers that are NOT adjacent (i.e., their absolute difference != 1). In other words, no two consecutive numbers can be placed in neighboring cells.
We need to output -1 if impossible, else any valid matrix.
Given example: n=1 works, n=2 impossible, n=3 possible as given.
We need to find general condition.
Observation: This is like a graph coloring or labeling problem. The grid graph is bipartite (like chessboard). Cells can be colored black/white such that neighbors are opposite color. Requirement: numbers that differ by 1 cannot be placed on adjacent cells. So if we consider the ordering of numbers 1..n^2, each number is adjacent to its predecessor and successor (except endpoints). So essentially we need to place numbers on a bipartite graph such that no edge connects two consecutive numbers.
Maybe we can treat it as a Hamiltonian path or something? Let's think.
We need to assign numbers to vertices of the grid graph such that the induced mapping has the property: for any edge uv, |f(u)-f(v)| != 1.
Equivalent: The graph formed by connecting numbers that differ by 1 is a path: 1-2-3-...-n^2. We want a vertex labeling f: V(Grid) -> {1,...,N} bijective such that there is no edge between vertices whose labels are consecutive. So f must be a graph homomorphism? Actually we want that the adjacency in grid does not correspond to adjacency in the path. So we want that the labeling is a graph embedding of the grid into the complement of the path? Hmm.
Simplify: We can think of a bipartition: black cells and white cells. In an n x n grid, if n is even, there are equal number of black and white cells: N/2 each. If n is odd, one color has one more cell: (N+1)/2 black, (N-1)/2 white (or vice versa). Usually number of black cells = ceil(N/2), white = floor(N/2) if top-left is black.
Now, the condition forbids placing consecutive numbers on neighboring cells. Since neighbors are always opposite colors, if we put all odd numbers on black cells and all even numbers on white cells, then any two numbers on adjacent cells would be odd/even, which are adjacent only if one is odd and the other is even with difference 1? Actually difference 1 implies one is odd and the other even. So if we place odds on black and evens on white, then adjacent cells (black-white) could potentially be odd-even and could be consecutive. For example, odd 1 and even 2 are consecutive and would be placed on adjacent cells if that assignment allowed. So to avoid adjacency, we must ensure that no odd-even pair that are consecutive appear on adjacent cells. However, if we place all odds on black and evens on white, then every edge connects odd to even; if we could arrange that the odd numbers adjacent to a given even number are not its consecutive odd, we need to avoid specific pairs.
Maybe a stronger condition: It may be possible to separate numbers into two sets such that numbers from set A are never adjacent to numbers from set B if they differ by 1? But that's messy.
Alternate viewpoint: We need to avoid edges between numbers that differ by 1. This is reminiscent of a graph labeling called "graceful labeling" or "lucky labeling"? Not exactly.
Perhaps we can construct for all n except 2? Let's test small n.
n=1: trivial.
n=2: grid 2x2 has 4 cells. We need to place numbers 1-4. Let's attempt: neighbors: each cell has 2 or 3 neighbors. We need to avoid consecutive numbers adjacent. Is it possible? Possibly not. Let's test manually. Cells: positions (1,1), (1,2), (2,1), (2,2). Suppose we try to assign. Consider 1's neighbors must not include 2. So 2 cannot be adjacent to 1. So 2 must be placed in a cell not adjacent to 1's cell. In a 2x2 grid, each cell is adjacent to two others (except? Actually corners each have 2 neighbors). There is no pair of cells that are not adjacent? Let's list adjacency: (1,1) adjacent to (1,2) and (2,1). (1,2) adjacent to (1,1) and (2,2). (2,1) adjacent to (1,1) and (2,2). (2,2) adjacent to (1,2) and (2,1). So each cell is adjacent to exactly two others. For any placement of 1, the cell that is not adjacent to it? Check: The cells not adjacent to (1,1) are (2,2) only? Because (1,1) adjacent to (1,2) and (2,1); not adjacent to (2,2). So there is exactly one cell not adjacent to a given cell. Similarly, for (1,2): not adjacent to (2,1); etc. So if we place 1 somewhere, 2 must be placed in the unique non-adjacent cell to 1. So that forces location of 2. Then we have two remaining cells for 3 and 4. These two remaining cells are adjacent? Check: Suppose 1 at (1,1), then 2 must be at (2,2). Remaining cells: (1,2) and (2,1). Those two are adjacent? They are not directly adjacent? (1,2) adjacent to (2,2) and (1,1). (2,1) adjacent to (1,1) and (2,2). They are not adjacent to each other? Actually (1,2) and (2,1) are diagonally adjacent, not sharing a side, so they are not adjacent. Good. So 3 and 4 can be placed arbitrarily, but must satisfy that adjacent cells between them and neighbors are okay. Let's test assignments.
After placing 1 at (1,1), 2 at (2,2). Now 3 and 4 go to (1,2) and (2,1). Constraints: For each placed number, its neighbors must not be consecutive. So check for 3: its neighbors are (1,1) with 1 (diff=2 okay), and (2,2) with 2 (diff=1? 3 and 2 diff=1, they are consecutive! So 3 cannot be adjacent to 2. But (3) at (1,2) is adjacent to (2,2) which contains 2. That would be invalid. Similarly, if 3 at (2,1), it is adjacent to (2,2) which contains 2, again diff=1. So any assignment of 3 in the remaining cells would be adjacent to 2. Also 4: 4 adjacent to 3 (if 3 is placed in the other cell? But 4 is not adjacent to 2? 4 at (1,2) adjacent to 2 (diff=2 okay) and 1 (diff=3). But also adjacent to the other cell? Actually (1,2) adjacent to (1,1) and (2,2) only, not to (2,1) because that's diagonal. So if we put 4 at (1,2), neighbors: 1 (ok), 2 (4-2=2 ok). So 4 is okay if 3 is not adjacent to 4? But 4's neighbors do not include 3. For 3 at (2,1), neighbors: 1 (diff=2 ok) and 2 (diff=1 invalid!). So 3 always invalid. Could we place 3 at (2,2)? No, already occupied. So this assignment fails. What if we choose different initial positions? By symmetry, it's the same. Could we place 1 and 2 not in opposite corners? Let's try 1 at (1,1), 2 at (1,2) would be adjacent (diff=1) not allowed. So 2 must be at non-adjacent cell to 1. As argued, for each cell, there is exactly one non-adjacent cell (the opposite corner). So 2 forced to opposite corner. So the configuration forced is that 1 and 2 are opposite corners. Then 3 and 4 go to the other two cells. But as we saw, both of those cells are adjacent to the cell containing 2? Let's check: if 2 is at (2,2), then (1,2) and (2,1) are both adjacent to (2,2). So any number placed there would be adjacent to 2. Since the only numbers left are 3 and 4, whichever is placed adjacent to 2 will have difference possibly 1 if it's 3? 3 diff 2 =1, 4 diff 2=2. So if we put 4 in a cell adjacent to 2, it's fine; but 3 must not be adjacent to 2. So we need to place 3 in a cell not adjacent to 2. But both remaining cells are adjacent to 2. So impossible. Could we have placed 2 at opposite corner and then assign 3 and 4 such that 3 is not adjacent to 2? No, because both remaining cells are adjacent to 2. So n=2 impossible. That matches sample.
Now n=3: sample given works. So not all n impossible.
Maybe pattern: n even? Let's test n=4. Is it possible? We can try to think about parity and counts.
Consider the concept: The condition forbids edges between consecutive numbers. The grid graph is bipartite. So we can color cells black and white. Let's denote B set and W set. For any edge, it's between B and W. So we need to assign numbers such that no edge connects i and i+1. That means that for each i from 1 to N-1, the positions of i and i+1 must be on the same color? Because if they are on opposite colors, then they could be adjacent, but not necessarily; they could be far apart. However, if they are on the same color, they are never adjacent (since adjacency only across colors). So a sufficient condition to guarantee that no consecutive numbers are adjacent is to place all consecutive numbers on the same color. But that's impossible because numbers are consecutive from 1 to N, and we have two colors. We could try to assign all odd numbers to black and evens to white; then consecutive numbers would be opposite colors, which potentially could be adjacent. But if we could arrange them such that whenever numbers are opposite colors, they are not placed on adjacent cells, maybe by careful arrangement.
Alternatively, we might assign numbers such that for each consecutive pair, they are on same color. That would mean that the entire set of numbers is partitioned into runs of same color. Since there are only two colors, we would need to alternate colors for consecutive numbers: e.g., 1 on black, then 2 also on black, then 3 on white? Wait if we want 1 and 2 on same color, and 2 and 3 also on same color, then 1 and 3 must be same color as well. That would force all numbers to be same color, impossible because colors have limited capacity. Actually, if we require that for each i, color(i) = color(i+1), then all numbers have same color, impossible because grid bipartite sets have different sizes (unless n=1). So we cannot have all consecutive pairs on same color.
So we need to allow some consecutive pairs to be on opposite colors, but then ensure that those opposite-colored cells are not adjacent.
Maybe there's a known result: For an n x n grid, a "non-consecutive adjacent" labeling exists for all n except n=2. I recall a problem from Codeforces: "Avoiding Adjacent Consecutive Numbers" maybe similar to CF Round #? Actually there is a problem called "Non-adjacent matrix" or something. I think the answer is that it's possible for all n except n=2. But we need to verify for n=4,5,... up to 100.
Let's test small cases manually using reasoning.
n=3 works (sample).
n=4: We need to place numbers 1..16. Check possibility.
We can attempt to construct a pattern. One idea: Fill matrix in a checkerboard pattern with two sequences: put all odd numbers on black cells, all even numbers on white cells. Then any edge connects odd and even. Consecutive numbers are odd-even, so they would be on opposite colors. That's not automatically problematic; we need to ensure that no odd is adjacent to its consecutive even neighbor. But perhaps we can order the odds and evens within each color to avoid adjacency of specific pairs.
Let's attempt to design a scheme.
Observation: If we place numbers in increasing order along a snake-like pattern (like typical matrix filling), consecutive numbers become adjacent in the snake, but they are physically adjacent along the snake path. That would cause adjacency if the snake moves to neighboring cells. So we need a filling where consecutive numbers are not neighbors.
Perhaps we can separate numbers by parity in a more extreme way: Put all numbers ≤ N/2 (or some threshold) on black cells, and numbers > N/2 on white cells. Then any two numbers with difference 1 would be either both in the same half (if they cross the threshold?) Actually if the threshold is k, numbers k and k+1 are on opposite halves if we split at k. Then they would be on opposite colors. But we need to avoid them being adjacent. If we ensure that all black cells are not adjacent to white cells that contain numbers close to them? But adjacency is between cells, not numbers.
Maybe we can design a pattern where numbers are arranged such that the grid is partitioned into two independent sets (colors) and we assign numbers in a way that consecutive numbers are placed far apart.
Another angle: Graph coloring of the "conflict" graph? Actually the condition is that the labeling is a proper coloring of the grid graph with respect to the graph of consecutive numbers? Not sure.
We can think of this as a kind of "L(2,1)" labeling? Not exactly.
Simplify: We need to output any valid matrix for given n. So we can develop an explicit construction that works for all n except 2. Let's try to construct for general n.
Idea: Use a pattern that fills the matrix in a chessboard manner with numbers from 1..N, but with a "checkerboard" of parity but also with a large gap between numbers on adjacent cells.
Maybe we can fill the matrix row by row with numbers that are not consecutive neighbors: e.g., fill all odd numbers first in black cells, then fill all even numbers in white cells. But we need to order them so that if an odd number x is placed, its neighboring white cells contain numbers that are not x+1 or x-1. Since evens are all >? Actually the evens set contains numbers that may be adjacent to some odds. For each odd number, its successor (odd+1) is an even number. So we need to ensure that for each odd, its neighbors (white cells) do not contain that specific even number. Similarly, for each even, its neighbors (black cells) do not contain the odd numbers adjacent to it (i.e., even-1 and even+1). So we need to assign the evens to white cells in such a way that for each black cell with odd value o, none of its neighboring white cells contain o+1. Similarly for each white cell with even value e, none of its neighboring black cells contain e-1 or e+1.
This is a kind of "matching" condition.
Perhaps we can achieve by a simple placement: Fill the matrix in increasing order from left to right, top to bottom, but then swap some pairs? Or maybe fill with numbers in a pattern like:
For n=3 sample:
2 9 7
4 6 3
1 8 5
Let's analyze this sample. Numbers: 1..9. Positions (row, col) 1-indexed:
(1,1)=2, (1,2)=9, (1,3)=7
(2,1)=4, (2,2)=6, (2,3)=3
(3,1)=1, (3,2)=8, (3,3)=5
Check adjacency constraints: For each neighbor pair, diff !=1.
List edges:
Row1: (1,1)-(1,2): 2-9 diff7; (1,2)-(1,3):9-7 diff2.
Row2: (2,1)-(2,2):4-6 diff2; (2,2)-(2,3):6-3 diff3.
Row3: (3,1)-(3,2):1-8 diff7; (3,2)-(3,3):8-5 diff3.
Columns: (1,1)-(2,1):2-4 diff2; (2,1)-(3,1):4-1 diff3; (1,2)-(2,2):9-6 diff3; (2,2)-(3,2):6-8 diff2; (1,3)-(2,3):7-3 diff4; (2,3)-(3,3):3-5 diff2.
All diffs >1. Works.
What pattern? Let's look at parity: Black cells if (i+j) even? Usually top-left (1,1) even sum? In sample, (1,1):2 even; (1,2):9 odd; (1,3):7 odd? Actually (1+1)=2 even => black? (1+2)=3 odd => white; (1+3)=4 even => black. So black cells: (1,1)=2 (even), (1,3)=7 (odd), (2,2)=6 (even), (3,1)=1 (odd), (3,3)=5 (odd). Mixed parity. White cells: (1,2)=9 odd, (2,1)=4 even, (2,3)=3 odd, (3,2)=8 even. So no clear separation by parity.
Maybe the construction fills the matrix with numbers in a specific order: For n=3, they placed small numbers near corners, large numbers in middle? Possibly it's a "magic" like 2 9 7; 4 6 3; 1 8 5. Not obvious.
Maybe we can find a general construction: For any n != 2, we can fill the matrix with numbers in the order of a "knight's move" or something.
Let's search memory: I recall a Codeforces problem "Matrix Problem" where the answer is to output -1 for n=2 else output a matrix where each adjacent cells differ by >1. I think there was a known solution: For odd n, fill rows with odd numbers first then even, or something. Or use pattern: Fill all odd numbers in one color and all even numbers in the other, but arrange them in increasing order in a chessboard pattern such that consecutive numbers are not adjacent. Actually consider: If we fill the board with numbers such that numbers on black cells are all from 1 to ceil(N/2) (or something) and numbers on white cells are from ceil(N/2)+1 to N, then any edge connects a small number to a large number, difference at least something. But if the split is exactly half, then the smallest difference between a black number and a white number is about N/2? Actually not; if black numbers are 1..k and white numbers are k+1..N, then the difference between a black number and a white number can be as small as 1 if k and k+1 are across the split. For example, if k = floor(N/2), then k and k+1 are consecutive. So if a black cell contains k and a neighboring white cell contains k+1, that's invalid. So we must ensure that the specific pair (k, k+1) are not placed in adjacent cells. So we need to avoid adjacency for that specific cross-split pair. Could we ensure that the numbers at the split are placed far apart? Possibly, if we control assignment.
Maybe we can assign numbers in a "checkerboard" but with two sequences: all numbers from 1 to N placed such that they are in two interleaved sequences: e.g., first fill all black cells with numbers in increasing order: 1,2,3,... (but that would put consecutive numbers on black cells, which are not adjacent to each other because black cells are not adjacent (they are independent set). But wait, black cells are not adjacent to each other? In a bipartite grid, cells of the same color are never adjacent (since edges only between opposite colors). Yes! So if we place all numbers in the same color, consecutive numbers are on same color, thus they are never adjacent because same-color cells are never neighbors. That would satisfy the condition perfectly! However, the problem is we have two colors; we need to place all numbers, but we could place all numbers on black cells only? But we have to use all cells; each cell must have a number. So we must also fill white cells. But if we fill white cells with numbers that are not adjacent to their neighbors? The issue: white cells are adjacent to black cells. So if we put numbers on white cells, they will be adjacent to some black cells. If the black cells contain numbers, then the white numbers must not be consecutive to those black numbers. So we can try to assign numbers to black cells from a set that has no consecutive numbers with the numbers on white cells. That is, the sets of numbers on black and white should be "separated" by at least 2, i.e., the minimum absolute difference between any black number and any white number should be at least 2. Because if there exists a black number b and a white number w such that |b-w|=1, and if those two cells are adjacent (they could be, depending on placement), it might cause violation. But if we also control adjacency such that those specific pairs are not placed in neighboring cells, we might avoid it. But to be safe, we could make the two sets such that all numbers in black are say small numbers (1..k) and all numbers in white are large numbers (k+2..N) with a gap of at least 1 between the maximum black and minimum white, i.e., max(black) < min(white)-1. Then any black-white pair would have difference at least 2. Since edges always connect black-white, this would guarantee no adjacent consecutive numbers, regardless of arrangement! But we must also consider that white-white and black-black edges don't exist, so fine. However, we need to use all numbers from 1 to N. So we need to partition the set {1,...,N} into two subsets A and B such that all numbers in A are at least 2 apart from all numbers in B (i.e., max(A) < min(B)-1 or max(B) < min(A)-1). And we need to assign A to one color and B to the other color, with sizes matching the color counts. Then any assignment (any bijection from A to black cells and B to white cells) will automatically satisfy the condition, because any edge is between A and B, and any a in A and b in B have |a-b| >=2? Not necessarily if we just have a gap condition. If max(A) < min(B)-1, then for any a in A, b in B, we have b >= min(B) > max(A)+1 >= a+? Actually if a <= max(A) and b >= min(B) and min(B) >= max(A)+2, then b - a >= 2. Also if a is in B and b in A similarly. So yes, all cross differences are at least 2. So condition satisfied.
Thus the problem reduces to: For given n, can we partition numbers 1..N into two sets A and B with sizes matching the bipartite cell counts (let black count = ceil(N/2) if (1,1) black? Actually we can choose which color gets which set; we can assign the larger set to the larger color if needed). And we need that max(A) < min(B)-1 or max(B) < min(A)-1. Essentially we need to separate the numbers into two intervals with a gap of at least 1 between them. Because if we have two intervals [1, p] and [p+2, N] (or [1, q] and [q+2, N]) then the condition holds: the gap between p and p+2 is at least 2 (difference 2). But note: we need the sizes to match exactly the counts of black and white cells. So we need to find an integer split point k such that one part (say lower numbers) has size equal to the count of one color, and the other part (higher numbers) has size equal to the other color, and there is a gap of at least 1 (i.e., we skip one number) between the two intervals. That means we need to find an integer s such that size of {1,2,...,s} = count of one color, and size of {s+2, s+3, ..., N} = count of the other color. Then we skip number s+1, which is not used. But we must use all numbers 1..N; we cannot skip any. So we cannot leave out a number. So we cannot have a gap; we must include all numbers. So the sets A and B must together be exactly {1..N}. If we want that for all a in A, b in B, |a-b| != 1, then it's necessary that there is no pair (a,b) with difference 1. That means that if we sort all numbers, the partition must be such that no two consecutive numbers belong to different sets? Wait: If we want that for any a in A and b in B, |a-b| != 1, then we must avoid having a = x and b = x+1 simultaneously in different sets. That means that for each consecutive pair (x, x+1), they cannot be split across the partition. So either both are in A or both are in B. Because if one is in A and the other in B, then there exists a pair (x, x+1) with one in A and one in B. However, this doesn't automatically cause a violation because those numbers might be placed on cells that are not adjacent. The condition only prohibits adjacency in the grid, not that they are in different sets per se. But if we want a construction that works regardless of assignment of numbers to cells within each color, we need to ensure that even if a black cell contains x and an adjacent white cell contains x+1, that would be invalid. But we can control placement to avoid that specific adjacency. If we assign numbers arbitrarily to cells of a given color, we cannot guarantee that for every cross pair (x, x+1) where x in A and x+1 in B, they won't be placed in adjacent cells. However, we could maybe arrange the assignment carefully to avoid that. So the simple "gap" condition is sufficient but not necessary. But it would make construction easy: if we can partition numbers into two sets with a gap, then any placement works. Since we need to output some matrix, we can also design placement more cleverly.
But can we partition 1..N into two sets of sizes matching the bipartite counts without a gap? Possibly not always. Let's see sizes: For n x n, N = n^2. The bipartite counts: For grid, if we color like chessboard, number of black cells = ceil(N/2), white = floor(N/2). More precisely, if n is even, N even, black = N/2, white = N/2. If n is odd, black = (N+1)/2, white = (N-1)/2 (assuming top-left black).
Now, can we partition 1..N into two sets A (size black) and B (size white) such that no two consecutive numbers are in different sets? That would require that all consecutive pairs are within same set. That implies that each set consists of blocks of consecutive numbers. But since the sets are of different sizes (for odd n), one set is larger by 1. Could we have a partition where all numbers from 1 to k are in A, and numbers from k+1 to N are in B? That would split the consecutive pair (k, k+1) across sets, which would cause a risk. But if we place them carefully, maybe we can avoid adjacency for that single pair. For even n, sets equal size, we could have A = odds, B = evens. That splits every consecutive pair across sets. That seems dangerous because many cross pairs exist. But perhaps we can arrange the assignment so that no adjacent cells contain an odd and the following even? Let's examine n=4: N=16. If we put all odds on black and evens on white, then each odd o has neighbors (white cells) that contain evens. For o=1, neighbor whites could contain 2, causing violation if placed adjacent. But maybe we can assign evens to white cells such that 2 is not adjacent to 1, etc. Is that possible? Possibly with careful mapping. But we need a systematic construction.
I recall a known construction for this problem: For n >= 3, we can fill the matrix with numbers in increasing order along a "diagonal" or "spiral" pattern that ensures that consecutive numbers are not adjacent. Let's try to derive.
Maybe there is a known result: It's possible for all n except 2. I think I've seen a Codeforces problem with exactly this. The solution: If n=2, output -1. Else, output a matrix where we put all odd numbers first in increasing order row-wise, then all even numbers after. Let's test for n=3: odds: 1,3,5,7,9; evens:2,4,6,8. If we put odds in some order, evens in another, can we satisfy? For n=3, sample does not follow that pattern.
Alternatively, there is a known construction: Fill the board with numbers in the order of a "knight's move" but that's messy.
Let's try to design a constructive algorithm.
We need to assign numbers to cells such that for each edge (u,v), |f(u)-f(v)| != 1. That is equivalent to saying that the function f is a graph homomorphism from the grid graph to the complement of the path graph P_N (where edges are between numbers that are not consecutive). But we need a bijection.
A different approach: treat numbers modulo something. For any adjacent cells, we want numbers not to be consecutive. So perhaps we can assign numbers such that the parity of row+col determines something like: numbers in black cells are all multiples of something? Hmm.
We can try to construct using two sequences: fill black cells with numbers that are, say, 1, 4, 5, 8, 9, 12, ... and white cells with 2, 3, 6, 7, 10, 11, ... But need to match counts.
Maybe we can think of "distance-2" coloring: In a grid, if we place numbers in a pattern where consecutive numbers are at least distance 2 in Manhattan distance, then they won't be adjacent. So we need a Hamiltonian path with step >1? Not exactly.
Another thought: If we fill the matrix row by row with numbers, but then swap each pair of adjacent numbers? For instance, for n=3, the natural row-major order is:
1 2 3
4 5 6
7 8 9
This has many adjacent consecutive numbers: (1,2), (2,3), (4,5), (5,6), (7,8), (8,9) horizontally, and vertical (1,4), (2,5), (3,6), (4,7), (5,8), (6,9) are consecutive. So many violations. To fix, we could rearrange numbers so that consecutive numbers are not adjacent. Possibly by reversing order in rows or columns.
Consider the pattern: fill the first row with even numbers, second row with odds, etc. For n=4, we could try: row1: 2,4,6,8; row2: 1,3,5,7; row3:10,12,14,16; row4:9,11,13,15. Then check adjacency between row1 and row2: pairs like (2,1) diff1 -> violation. So not good.
Maybe we can use a "checkerboard" of two sequences: fill black cells with numbers 1,2,3,... in some order, and white cells with numbers N, N-1, N-2,... in reverse order, so that black and white numbers are far apart. But then consecutive numbers within the same color might be adjacent? They are not adjacent because same color cells are not neighbors. So that would be safe: if we assign all numbers to black cells (size = ceil(N/2)) and all numbers to white cells (size = floor(N/2)), but we have to use all numbers exactly once. So we need to split numbers into two groups: one group assigned to black cells, the other to white cells. The condition we need to avoid: for any edge (black, white), the numbers must not be consecutive. So if we make the black group consist of small numbers and white group consist of large numbers, then the differences are large and not 1. But as noted, if the split is at some k, the pair (k, k+1) are in different groups and could be adjacent; but if the gap between the max of the small group and the min of the large group is >1, then no consecutive numbers are across groups. However, we cannot have a gap because we must use all numbers. But we can arrange that the split point is not a single number; we can intermix: maybe assign numbers to black and white in such a way that the sets are not intervals but interleaved but still guarantee that for any black-white edge, the numbers are not consecutive. This is more flexible: we just need to avoid placing specific cross pairs on adjacent cells.
Given we can choose which number goes to which cell, we can try to construct for each n.
Maybe there is a known solution: For odd n, we can fill the matrix with numbers in a spiral order starting from the center, or something. Or we can use a pattern: for any n, we can fill the matrix with numbers in a "checkerboard" pattern where the numbers increase by 2 each step, but then we need to fill the remaining numbers on the other color also with increments of 2, but we must avoid adjacency with opposite color numbers being consecutive.
Let's test n=4 manually with a possible systematic approach.
Approach: Fill black cells (say (i+j) even) with numbers in increasing order: assign 1,2,3,...,B to black cells (B = number of black cells). Fill white cells with numbers B+1, B+2, ..., N. Then check adjacency: For any edge between a black cell with value x and a white cell with value y, we need |x-y| != 1. Since x ≤ B and y ≥ B+1, the only potential problem is if x = B and y = B+1 (difference 1). So if we can ensure that the black cell containing B is not adjacent to the white cell containing B+1, then maybe the construction works. All other pairs have difference at least 2? Not necessarily: If B=8 (for n=4, N=16, black count? For 4x4, black = 8, white = 8). So B=8. Then black numbers: 1..8, white: 9..16. Differences: For black 8 and white 9, diff=1. For any other combination: e.g., black 7 and white 9 diff=2, also could be diff=1? 7 and 8? No, 8 is black, not white. So only cross pair with diff 1 is (8,9). So if we can place 8 and 9 on cells that are not adjacent, we can avoid violation. But is it possible to place all black numbers arbitrarily on black cells and all white numbers arbitrarily on white cells, and specifically ensure that the positions of 8 and 9 are not adjacent? Since we have control, we can choose positions. So we need to find an assignment of numbers 1..8 to black cells and 9..16 to white cells such that no black-white adjacent cells contain numbers that differ by 1. The only dangerous difference is 1 between 8 and 9. Additionally, could there be other diff 1? For example, black 1 and white 2? But 2 is black (since 2 ≤8) so not white. White numbers start at 9, so 1 and 2 are both black, and 2 and 3 are black, etc. So indeed the only cross difference of 1 is between 8 and 9. However, we also need to consider that within same color, numbers can be consecutive (e.g., 1 and 2 both black) but they are not adjacent because same color cells are not neighbors. So that's fine.
Thus for even n, with equal black/white counts, if we assign the first half numbers (1..N/2) to black cells, and the second half (N/2+1 .. N) to white cells, the only potential adjacency issue is between the largest black (N/2) and the smallest white (N/2+1). So we need to place those two numbers on cells that are not adjacent. Since we can choose assignments, we can likely do that for all even n > 2? For n=2, N/2=2, black=2, white=2? Actually 2x2 grid: black cells? (1,1) black, (1,2) white, (2,1) white, (2,2) black? Let's define standard: (i+j) even = black. For 2x2, black cells: (1,1) and (2,2) – two black; white cells: (1,2) and (2,1) – two white. So black count =2, white=2. Then assign black numbers: 1,2; white numbers: 3,4. The dangerous pair is 2 (black) and 3 (white). Are there any adjacent black-white pair that could host 2 and 3? We can try to place 2 on a black cell and 3 on a white cell that is not adjacent. But all white cells are adjacent to some black cells. However, we can choose which black gets 2 and which white gets 3. The black cells are (1,1) and (2,2). White cells are (1,2) and (2,1). Check adjacency: (1,1) adjacent to (1,2) and (2,1). (2,2) adjacent to (1,2) and (2,1). So any white cell is adjacent to both black cells? Actually (1,2) adjacent to (1,1) and (2,2)?? (1,2) adjacent to (1,1) and (2,2)? Wait (1,2) adjacent to (1,1) horizontally, and (2,2) vertically? (1,2) down is (2,2), so yes (1,2) adjacent to (2,2) as well? Actually (1,2) down is (2,2), so yes (1,2) is adjacent to both (1,1) and (2,2). Similarly, (2,1) adjacent to (1,1) and (2,2). So each white cell is adjacent to both black cells. Therefore, if we place 2 on any black cell, then any placement of 3 on any white cell will be adjacent to that black cell because both white cells are adjacent to that black cell? Let's check: Suppose we put 2 on (1,1). Then white cells: (1,2) and (2,1) both adjacent to (1,1). So 3 placed on either white cell would be adjacent to 2 -> violation. Similarly if 2 on (2,2), then both white cells are adjacent to (2,2). So impossible. So n=2 fails.
For n=4, black count =8, white count=8. We need to assign numbers 1..8 to black cells, 9..16 to white cells, and ensure that the black cell containing 8 is not adjacent to the white cell containing 9. Is that possible? Let's analyze adjacency in 4x4 grid. Black cells (i+j even): (1,1), (1,3), (2,2), (2,4), (3,1), (3,3), (4,2), (4,4). White cells (i+j odd): (1,2), (1,4), (2,1), (2,3), (3,2), (3,4), (4,1), (4,3). We need to choose a black cell for 8 and a white cell for 9 such that they are not adjacent. Since we have many choices, likely possible. For example, put 8 on (1,1) black; adjacent white cells are (1,2) and (2,1). So we could put 9 on a white cell not among those, say (3,2) or (4,3) etc. So yes, possible. Additionally, we need to assign the other numbers arbitrarily; no other cross diff 1. So this simple partition works for n=4, provided we can avoid adjacency for that specific pair. So we can construct for any even n > 2? Let's test n=6: black count=18, white count=18 (since N=36, even). Partition: assign 1..18 to black, 19..36 to white. Dangerous pair: 18 (black) and 19 (white). We need to place 18 and 19 on non-adjacent cells. Is that always possible? Likely yes, because we have many cells; we can choose a black cell that has at least one white neighbor that is not the only white cell? But we need to avoid adjacency between those specific two cells. Since we can choose any black cell for 18 and any white cell for 19, as long as there exists at least one black cell and one white cell that are not adjacent, we can do it. In a grid, are there any black and white cells that are not adjacent? Possibly yes: For example, black cell (1,1) is adjacent to white cells (1,2) and (2,1). So there are many white cells not adjacent to (1,1): e.g., (1,4), (2,3), etc. So we can always choose a pair that are not adjacent. However, we must also ensure that all other numbers assigned arbitrarily do not create a diff 1 across colors? Only 18 and 19 are cross difference of 1? Let's confirm: Since black set = {1,...,18}, white set = {19,...,36}. For any black b and white w, the difference w - b >= 19-18 =1? Actually the minimum possible w - b is 19-18=1, which occurs only for b=18,w=19. For b=17,w=19 diff=2; b=18,w=20 diff=2; b=17,w=18 not cross; etc. So indeed only pair with diff 1 is (18,19). So we only need to ensure that the cells containing 18 and 19 are not adjacent. That seems easy.
But wait: What about negative difference? |b-w| could be 1 if b=20? But 20 is in white set? Actually white set starts at 19, so 20 is white, b max is 18, so b=18 and w=19 diff1; b=17 and w=18? 18 is black, so not cross. So yes only one cross pair.
Thus for even n >= 4, this scheme should work.
Now for odd n: n is odd, say n=3,5,7,... N = n^2 is odd. Bipartite counts: one color has (N+1)/2 cells, the other has (N-1)/2 cells. Let's decide which color is larger. Usually top-left black gives: for odd n, black = (N+1)/2, white = (N-1)/2 (since corners are black). So black has one more cell.
Now if we assign numbers to colors with a split, we need to match the sizes. We could assign the smaller set of numbers to the smaller color, and the larger set to the larger color. For a partition into two intervals with a gap, we can't have equal sizes because one set is larger. But we can still assign intervals: e.g., assign numbers 1..k to the larger color, and numbers k+? to the smaller color, but we need to use all numbers without gap. Suppose we let larger color get the first L numbers (1..L) and smaller color get the rest (L+1..N). Then sizes: L = (N+1)/2, N-L = (N-1)/2. That's exactly right. So we can set L = ceil(N/2) = (N+1)/2. So assign numbers 1..L to black (larger set), and numbers L+1..N to white (smaller set). Then the dangerous cross difference is between L (the largest in black) and L+1 (the smallest in white). That's a diff of 1. So again we have a single dangerous pair (L, L+1). Also, are there any other cross differences of 1? Consider L-1 (black) and L (black) not cross; L+1 (white) and L+2 (white) not cross. So only (L, L+1). So for odd n, we need to place L and L+1 on non-adjacent cells (one black, one white). That should be possible for n >= 3? For n=3, L = (9+1)/2 = 5, so black gets 1..5, white gets 6..9. Dangerous pair (5,6). In sample matrix, check: black cells (1,1)=2, (1,3)=7, (2,2)=6, (3,1)=1, (3,3)=5. White cells: (1,2)=9, (2,1)=4, (2,3)=3, (3,2)=8. Where are 5 and 6? 5 is at (3,3) black? Actually (3,3) sum=6 even -> black? (3+3=6 even, yes black) contains 5. 6 is at (2,2) sum=4 even -> black? Wait (2,2)=4 even, black. But 6 is in black? According to our scheme, 6 would be in white (since L=5, white = 6..9). But in the sample, 6 is at (2,2) which is black. So sample does not follow this partition. But that's fine; it's just another construction. In our scheme, we want to assign 1..5 to black, 6..9 to white. But 5 and 6 would then be on opposite colors. We need them non-adjacent. In a 3x3 grid, can we assign numbers such that black cells get 1..5 and white cells get 6..9, and 5 and 6 are non-adjacent? Let's see black cells: positions (1,1), (1,3), (2,2), (3,1), (3,3). White cells: (1,2), (2,1), (2,3), (3,2). Now we need to place 5 (black) and 6 (white) such that they are not adjacent. Is it possible? Let's examine adjacency: Each black cell is adjacent to some white cells. For (1,1) adjacent white: (1,2), (2,1). For (1,3): (1,2), (2,3). For (2,2): adjacent to all four white? Actually (2,2) adjacent to (1,2), (2,1), (2,3), (3,2) — all four white cells. So if we put 5 on (2,2), then any placement of 6 on any white cell would be adjacent -> violation. So we must avoid putting 5 on (2,2). For other black cells, they have only two white neighbors. For (1,1): neighbors (1,2) and (2,1). So if we put 5 at (1,1), then we can put 6 at a white cell not among those two, e.g., (2,3) or (3,2). But is (3,2) white? (3,2) sum=5 odd -> yes white. And (3,2) adjacent to (1,1)? No, distance. So that works. So we can choose 5 at (1,1) and 6 at (2,3) (white). Then assign the rest numbers arbitrarily: other black cells get 1,2,3,4; white cells get 7,8,9. Since only cross diff 1 is between 5 and 6 (which we placed non-adjacent), other cross differences are at least 2? Check: black numbers are 1-5, white numbers 6-9. For black 4 and white 6 diff=2, that's okay even if they are adjacent because diff=2 >1? Wait condition: numbers must not be adjacent, i.e., |a-b| != 1. So diff=2 is allowed. So that's fine. So this scheme works for n=3.
But need to ensure that for black numbers 1..5, white numbers 6..9, any adjacent black-white pair besides (5,6) could have diff=1? Let's examine: Could there be black 5 and white 4? No 4 is black. So only (5,6) has diff 1. Also black 5 and white 6 diff1; black 4 and white 5? 5 is black, so not. But what about black 5 and white 4? Not cross. So yes only one dangerous pair.
Thus for any odd n >= 3, we can use the same scheme: assign numbers 1..ceil(N/2) to black cells (or the larger color), assign the rest to white cells, and place the two numbers ceil(N/2) and ceil(N/2)+1 on non-adjacent cells. The question: is it always possible to choose non-adjacent cells for these two numbers? For n=1, trivial (only one cell, but N=1, no adjacent). For n=3, we argued possible as long as we avoid the central cell (2,2) for the larger black number? Actually careful: For odd n, the central cell (if n odd) is at ((n+1)/2, (n+1)/2). Its coordinates sum = n+1, which is even if n odd? Let's compute: n odd, say n=5, (3,3) sum=6 even -> black. So the central cell is black and is adjacent to all four white cells around it (since it's interior). So if we put the large black number L at the center, then it would be adjacent to all white cells, making it impossible to place L+1 on a white cell without adjacency. So we must avoid placing L at the center black cell (if that cell is black). But if we assign L to a different black cell that is not adjacent to all white cells, we can choose a white cell not adjacent to that black cell. Is it always possible to find a black cell and a white cell that are not adjacent? In a grid, there always exist pairs of opposite color cells that are not adjacent, e.g., a black cell in one corner and a white cell in the opposite corner (like (1,1) black and (n,n) white? For odd n, (n,n) sum = 2n even, so black? Actually (n,n) with n odd: n+n=2n even, so black. So opposite corner is same color. We need black-white pair not adjacent. For example, black at (1,1) and white at (1,3) for n=3? (1,3) is black? (1+3=4 even) black. So need white. White cells: (1,2) adjacent to (1,1). But (2,3) white? (2+3=5 odd) white; is (2,3) adjacent to (1,1)? No, distance >1. So pair (1,1) black and (2,3) white are not adjacent. So we can find such. For n=5, black cell (1,1) and white cell (5,4) maybe not adjacent. Generally, we can choose black cell at (1,1) and white cell at (n, n-1) if that is white? For n odd, n is odd, n-1 even, so (n, n-1) sum = 2n-1 odd -> white. (1,1) and (n, n-1) are far apart, not adjacent. So definitely possible.
Thus the simple partition scheme works for all n except n=2? Also check n=1: N=1, black count=1, white count=0. Partition: assign numbers 1..1 to black, nothing to white. No edges. So works. So only n=2 fails because the geometry forces any black and white cells to be adjacent? Actually in 2x2, every black cell is adjacent to all white cells? Yes, each black cell is adjacent to both white cells, and each white cell adjacent to both black cells. So any assignment of L and L+1 to opposite colors will inevitably be adjacent, because for any black cell, all white cells are adjacent to it. So we cannot avoid adjacency of that pair. Thus n=2 fails.
But what about other even n? For n=4, we saw it's possible. In 4x4, each black cell is adjacent to some white cells, but not all white cells. So we can pick a black cell that is not adjacent to all white cells, and then pick a white cell not adjacent to it. For example, black (1,1) is adjacent only to (1,2) and (2,1). Many white cells not adjacent. So works.
Thus the condition for success is: There exists a black cell and a white cell that are not adjacent. For a grid, when n >= 3, such a pair exists. For n=1, trivial. For n=2, every black cell is adjacent to every white cell (each black adjacent to both whites). So fails.
Therefore, a simple construction: for each n != 2, we can produce a matrix by:
- Color cells by chessboard: (i+j) even -> black, odd -> white.
- Let B = number of black cells = ceil(n^2/2), W = floor(n^2/2).
- Assign numbers 1..B to black cells (any order) and numbers B+1..n^2 to white cells (any order), but with the additional condition: ensure that the cell containing B (the largest black) and the cell containing B+1 (the smallest white) are not adjacent.
- We can achieve this by placing B at a black cell that is not adjacent to all white cells (i.e., not a black cell that is adjacent to every white cell), and placing B+1 at a white cell not adjacent to that black cell.
- For n >= 3, we can choose for example: place B at black cell (1,1) (if (1,1) is black; it is), and place B+1 at white cell (n, n) if (n,n) is white? Let's check parity: For any n, (n,n) sum = 2n, which is even, so it is black if we define black = even sum. So (n,n) is black, not white. We need a white cell not adjacent to (1,1). For even n, (n, n-1) is white? n even, n-1 odd, sum = 2n-1 odd -> white. Is (n, n-1) adjacent to (1,1)? No. So we can place B+1 there. For odd n, white cells include (n, n-1) as well? n odd, n-1 even, sum = 2n-1 odd -> white. So yes (n, n-1) is white and not adjacent to (1,1). So that works.
But careful: For odd n, B = (n^2+1)/2. So B is quite large. We'll place B at (1,1) and B+1 at (n, n-1). But we must ensure that (1,1) is black. Yes. And (n, n-1) is white? Check parity: (n + n-1) = 2n-1, always odd, so white. So that's fine. They are not adjacent because Manhattan distance >1. So condition satisfied.
Now we need to assign the rest numbers arbitrarily to the remaining cells of each color. That will give a valid matrix.
But we must verify: Are there any other potential cross differences of 1? No, because black set is 1..B, white set is B+1..N. The only consecutive cross numbers are B and B+1. So only that pair can cause violation. By ensuring they are not adjacent, we guarantee all edges are safe.
Thus this construction works for all n except n=2. Also n=1 works trivially because B=1, W=0, no edges.
Now we should also check for n=2: B=2, W=2. The sets are {1,2} black, {3,4} white. But as argued, every black cell is adjacent to all white cells, so B and B+1 must be adjacent regardless of choice, impossible. So -1.
Thus answer: For n=1 and n>=3, output a matrix using this construction.
But we need to output a matrix explicitly. We should describe an algorithm to fill numbers.
Simple method:
- Compute N = n*n.
- Determine black cells (i+j even) and white cells (i+j odd).
- Let B = (N+1)//2 (ceil). Actually we need B = number of black cells. But we can compute black count = (nn+1)//2, white = (nn)//2.
- We'll assign numbers 1..B to black cells and B+1..N to white cells.
- We need to place B and B+1 on non-adjacent cells of opposite colors.
- Choose a specific black cell for B, say (1,1) (since it's black). (If n=1, then B=1, and (1,1) is the only cell, but B+1 doesn't exist; that's fine.)
- Choose a specific white cell for B+1 that is not adjacent to (1,1). For n>=3, we can choose (n, n-1) as white (if n>1). For n even, (n, n-1) is white; for n odd, also white. Check adjacency: (1,1) and (n, n-1) are far apart, not adjacent.
- For the remaining black cells, we assign the other black numbers (1..B-1) in any order (e.g., row-major order or just increasing order over the black cells, skipping the chosen cell for B). Similarly for white cells, assign the other white numbers (B+2..N) to remaining white cells, skipping the chosen cell for B+1.
- But we must ensure that the assignment for black numbers does not accidentally place any other number adjacent to something that creates a diff 1? Since only cross diff 1 is between B and B+1, and we've taken care, all other cross differences are at least 2. However, we should also consider that within same color, numbers could be consecutive? But same color cells are never adjacent, so fine. So any arrangement works.
Potential nuance: For odd n, black count = (N+1)/2, white = (N-1)/2. B = (N+1)/2. So B is the largest black number, and B+1 is smallest white. We assign B to (1,1). But (1,1) is black, good. Then we assign B+1 to (n, n-1) which is white. All other numbers are placed arbitrarily.
Now verify for n=3: N=9, B=5, W=4. So black numbers:1,2,3,4,5; white numbers:6,7,8,9. Place B=5 at (1,1). Place B+1=6 at (3,2) (since n=3, n-1=2, so (3,2) is white). Check adjacency: (1,1) and (3,2) are not adjacent (Manhattan distance |1-3|+|1-2|=3). Good.
Now fill remaining black cells: black cells list: (1,1) taken, other black cells: (1,3), (2,2), (3,1), (3,3). Assign numbers 1,2,3,4 arbitrarily. Let's assign in order as we iterate rows: e.g., for each cell in row-major order, if it's black and not taken, assign next black number. Similarly for white.
Let's test the resulting matrix to see if any diff 1 occurs. Example: n=3. Black cells: (1,1)=5 (B), (1,3)=? we assign 1, (2,2)=2, (3,1)=3, (3,3)=4. White cells: (1,2)=6? Actually (1,2) is white; but we placed B+1=6 at (3,2). So (1,2) will get another white number, say 7, (2,1)=8, (2,3)=9, (3,2)=6. This yields matrix:
Row1: (1,1)=5, (1,2)=7, (1,3)=1
Row2: (2,1)=8, (2,2)=2, (2,3)=9
Row3: (3,1)=3, (3,2)=6, (3,3)=4
Check adjacency constraints: Let's test each edge:
(1,1)-(1,2):5-7=2 ok; (1,2)-(1,3):7-1=6 ok.
(2,1)-(2,2):8-2=6; (2,2)-(2,3):2-9=7.
(3,1)-(3,2):3-6=3; (3,2)-(3,3):6-4=2.
Vertical: (1,1)-(2,1):5-8=3; (2,1)-(3,1):8-3=5; (1,2)-(2,2):7-2=5; (2,2)-(3,2):2-6=4; (1,3)-(2,3):1-9=8; (2,3)-(3,3):9-4=5.
All good! So it works.
Now for n=4: N=16, B=8, W=8. Place B=8 at (1,1). Place B+1=9 at (4,3) (since n=4, n-1=3). Check (1,1) and (4,3) not adjacent. Now assign other blacks: black cells except (1,1): (1,3), (2,2), (2,4), (3,1), (3,3), (4,2), (4,4). That's 7 cells, assign numbers 1..7 arbitrarily. White cells except (4,3): (1,2), (1,4), (2,1), (2,3), (3,2), (3,4), (4,1). That's 7 cells, assign numbers 10..16? Wait B+1=9 placed, remaining white numbers are 10..16 (7 numbers). So assign those arbitrarily.
Check potential diff 1 across edges: Only cross diff 1 pair is (8,9). Since they are not adjacent, fine. All other cross differences: min difference is 2 (e.g., 7 black vs 10 white diff=3; 8 black vs 10 diff=2; 7 vs 9 diff=2). So safe. Within colors, no adjacency. So valid.
Now for n=5: N=25, B=13, W=12. Place B=13 at (1,1). Place B+1=14 at (5,4) (since n=5, n-1=4). (5,4) white? (5+4=9 odd) white. Not adjacent. Assign other blacks 1..12 to remaining black cells (total black cells count = 13, so 12 left). White numbers 15..25 to remaining white cells (12 cells). All cross differences: The smallest white is 15, largest black (except 13) is 12, diff=3; but black 13 and white 14 are the only diff1 pair, placed non-adjacent. Also consider black 13 and white 15 diff=2; that's allowed. So safe.
Thus this construction works for all n except 2.
But we must also consider n=1: B=1, W=0. Place 1 at (1,1) (the only cell). No issues.
So answer: For each test case, if n == 2, output -1; else, output a matrix constructed as described.
Now, we should produce a clear method to generate matrix in code.
Implementation details:
-
For given n, compute N = n*n.
-
Determine blackCount = (N+1)//2, whiteCount = N//2.
-
Choose black position for L = blackCount (the max black). We'll use (0,0) in 0-indexed? But careful with parity. Let's define indices from 0 to n-1. Then color can be determined by (i+j) % 2 == 0 as black (or whatever). We need consistent: If we set (0,0) as black (since 0+0=0 even), then indeed it's black. So we can use 0-indexed.
-
Choose white position for L+1. We want a white cell far from (0,0). Good candidate: (n-1, n-2) if n>=3. Check parity: (n-1)+(n-2) = 2n-3. Since n>=3, 2n-3 is odd? Actually 2n is even, minus 3 gives odd, so (n-1, n-2) is white. Also (n-1, n-2) is not adjacent to (0,0) because Manhattan distance = (n-1)+(n-2) = 2n-3 >= 3 for n>=3, so not adjacent. For n=3, (2,1) is white, distance = 2+1=3, not adjacent. So good.
-
However, we need to ensure that (n-1, n-2) is within bounds (n>=2). For n>=3 it's fine. For n=1, we don't need this.
Alternative for even n: Could also use (0,1) is white but that's adjacent to (0,0), so not that. So (n-1, n-2) is safe.
- But what about n=4, (3,2) is white? (3+2=5 odd) white, good.
Thus we can fix: special_black = (0,0); special_white = (n-1, n-2).
But we need to ensure that special_white is indeed a white cell. For n=4, (3,2): 3+2=5 odd -> white. Good.
Edge case: n=2? Not used.
Edge case: n=1? Then special_white is (0, -1) invalid. So we handle n=1 separately: just output 1.
Now algorithm steps:
- Initialize matrix with zeros (size n x n).
- Create two lists: black_cells and white_cells (or we can directly assign while iterating). But we need to assign numbers in some order.
Simpler: We'll iterate over all cells in row-major order (i from 0 to n-1, j from 0 to n-1). We'll have two counters: black_counter = 1 (starting from 1) and white_counter = blackCount+1 (starting from blackCount+1). But we must skip the special positions for the largest black and smallest white.
So:
-
Let black_max = blackCount; // the number that goes to special_black
-
Let white_min = blackCount+1; // the number that goes to special_white
-
We'll assign matrix[special_black] = black_max.
-
We'll assign matrix[special_white] = white_min.
Now for all other cells:
- For black cells (except special_black): assign numbers from 1 to blackCount-1 in some order.
- For white cells (except special_white): assign numbers from white_min+1 to N in some order.
We need to assign these numbers without conflict. A simple method: iterate over all cells in some order (e.g., row-major) and if cell is black and not special_black, assign the next available black number (starting from 1). Similarly, if white and not special_white, assign the next available white number (starting from white_min+1).
This will fill all cells correctly.
We need to ensure we correctly identify black/white cells based on parity. Using (i+j)%2 == 0 as black (since (0,0) even -> black). That matches our assignment.
Now test for n=3:
- blackCount = (9+1)//2 =5, whiteCount=4.
- special_black=(0,0) -> assign 5.
- special_white=(2,1) -> assign 6.
- Iterate row-major:
i=0,j=0: special, skip assignment later? We'll assign directly before loop. We'll set these two cells beforehand and then skip them in loop.
Proceed:
i=0,j=1: (0+1)%2=1 -> white, not special? special_white is (2,1) so no. Assign next white number: white numbers start from 7? Actually white_min+1 = 6+1=7. So assign 7. white_counter increments to 8.
i=0,j=2: (0+2)%2=0 -> black, not special? (0,2) not special (special_black is (0,0)). Assign next black number: black numbers start from 1. So assign 1. black_counter increments to 2.
i=1,j=0: (1+0)%2=1 -> white, not special? (1,0) not special, assign next white number: 8. white_counter ->9.
i=1,j=1: (1+1)%2=0 -> black, not special? (1,1) not special, assign next black number: 2. black_counter->3.
i=1,j=2: (1+2)%2=1 -> white, assign next white: 9. white_counter->10 (but white numbers only up to 9? Actually white numbers go from 7 to 9? Wait total white numbers: whiteCount=4, we have already assigned one special white=6, remaining white numbers = 7,8,9. So after assigning 7,8,9, done. So white_counter will stop at 9+1=10 but that's fine, we only assign three more.
i=2,j=0: (2+0)%2=0 -> black, not special? (2,0) not special, assign next black: 3. black_counter->4.
i=2,j=1: special_white already assigned.
i=2,j=2: (2+2)%2=0 -> black, not special? (2,2) not special, assign next black: 4. black_counter->5 (but black numbers total blackCount=5, we assigned special=5, and then 1,2,3,4 = 4 more, so all assigned). So final matrix:
(0,0)=5, (0,1)=7, (0,2)=1
(1,0)=8, (1,1)=2, (1,2)=9
(2,0)=3, (2,1)=6, (2,2)=4
That's the same as our earlier example (just rows/cols permuted? Actually earlier we had row1:5 7 1; row2:8 2 9; row3:3 6 4). Yes matches. And we checked it's valid.
Now test n=4:
- blackCount = (16+1)//2 = 8? Actually N=16, (16+1)//2=8? (16+1)/2=8.5 floor? integer division: (16+1)//2 = 8? Actually in integer division, (16+1)//2 = 17//2 = 8. So blackCount=8, whiteCount=8.
- special_black=(0,0) assign 8.
- special_white=(3,2) assign 9.
- Then iterate.
We need to ensure that black numbers 1..7 assigned to remaining black cells; white numbers 10..16 to remaining white cells.
Let's simulate quickly mentally:
Black cells list (0-index):
(0,0) special
(0,2)
(1,1)
(1,3)
(2,0)
(2,2)
(3,1)
(3,3)
White cells:
(0,1)
(0,3)
(1,0)
(1,2)
(2,1)
(2,3)
(3,0)
(3,2) special
Remaining white cells: 7 cells, assign 10,11,12,13,14,15,16 in order. Remaining black cells: 7 cells, assign 1..7.
Now check any cross diff 1? Only 8-9 pair, which are at (0,0) and (3,2) not adjacent. Good.
But need to ensure that (0,0) is not adjacent to (3,2) indeed: distance = 3+2=5 >1.
Thus works.
Now n=5:
- blackCount = (25+1)//2 = 13, whiteCount=12.
- special_black=(0,0)=13
- special_white=(4,3)=14
- remaining black: 12 cells assign 1..12
- remaining white: 11 cells assign 15..25
Works.
Now n=6: blackCount = (36+1)//2 = 18? Actually (36+1)//2=18? 37//2=18, so black=18, white=18. special_black=(0,0)=18, special_white=(5,4)=19. Then remaining black: 17 cells assign 1..17, remaining white: 17 cells assign 20..36. Check cross diff 1 only (18,19). Are they non-adjacent? (0,0) and (5,4) distance 5+4=9 >1, fine.
So seems all n>=3 work.
But we must also consider n=2: In our construction, if we attempted, blackCount=2, whiteCount=2, special_black=(0,0)=2, special_white=(1,0)? Actually for n=2, our special_white candidate (n-1, n-2) = (1,0). Check parity: (1+0)=1 odd -> white. But (0,0) and (1,0) are adjacent! So they would be adjacent, causing violation. Could we pick a different white cell that is not adjacent to (0,0)? For n=2, white cells are (0,1) and (1,0). Both are adjacent to (0,0): (0,1) adjacent horizontally, (1,0) adjacent vertically. So indeed impossible. So n=2 impossible.
Thus the construction is valid.
Now we should verify for n=1: blackCount = (1+1)//2 =1, whiteCount=0. special_black = (0,0) assign 1. special_white not used. No loop for white. Should output matrix with single 1. Works.
So algorithm:
For each test case:
- read n.
- if n == 2: print -1.
- else:
- Initialize matrix n x n with zeros.
- Compute B = (n*n + 1) // 2 (number of black cells)
- Set max_black = B, min_white = B+1 (if B < n*n; if n=1, B=1, min_white would be 2 but no white cells; we'll handle by only assigning white cells if exist.)
- Set special_black = (0,0) (0-indexed). Set matrix[0][0] = max_black.
- If n > 1: special_white = (n-1, n-2). Set matrix[special_white] = min_white.
- Initialize two counters:
black_next = 1 (next black number to assign, excluding max_black)
white_next = min_white + 1 (next white number, excluding min_white)
- Iterate for i in 0..n-1, j in 0..n-1:
if (i,j) == special_black or (i,j) == special_white: continue
if (i+j) % 2 == 0: # black cell
matrix[i][j] = black_next
black_next += 1
else: # white cell
if min_white <= nn: # but only if white_next <= nn, which it will
matrix[i][j] = white_next
white_next += 1
- Output matrix.
But we need to ensure that we assign all numbers correctly and that black_next ends at B-1, white_next ends at N. Since counts match, it's fine.
Double-check counts: For n even, B = N/2. Then number of remaining black cells = B - 1 (since special_black taken). black numbers to assign = B - 1 (from 1 to B-1). That matches. Number of remaining white cells = B - 1? For n even, white count = B, but special_white taken, so remaining white cells = B - 1. white numbers to assign = N - (B+1) + 1? Actually numbers from min_white+1 to N inclusive: count = N - (B+1) + 1 = N - B = B (since N=2B). That would be B numbers, but we only have B-1 white cells left. Wait miscalculation: For n even, N=2B. B = N/2. So black count = B, white count = B. We assign max_black = B to special_black. Then remaining black cells = B-1, black numbers 1..B-1 count = B-1 -> good.
White: we assign min_white = B+1 to special_white. Then remaining white cells = B-1. The remaining white numbers should be from B+2 to N = 2B. Count = 2B - (B+2) + 1 = B - 1. So white numbers count = B-1. Good. So we need to assign numbers from B+2 to 2B. So white_next should start at B+2. In our earlier we set white_next = min_white+1 = B+2. Correct.
For n odd: N=2B-1? Let's derive: N = n^2 odd, B = (N+1)/2 = (N+1)/2, so N = 2B - 1. Black count = B, white count = B-1. We assign max_black = B to special_black. Remaining black cells = B-1, assign numbers 1..B-1 (count B-1). White: assign min_white = B+1 to special_white. But white count = B-1, so we have B-2 remaining white cells? Wait careful: white count = B-1. We assign one white cell (special_white) with min_white = B+1. So remaining white cells = (B-1) - 1 = B-2. The remaining white numbers: from B+2 to N = 2B-1. Count = (2B-1) - (B+2) + 1 = B - 2. Yes matches. So white_next start = B+2.
Thus our assignment works.
Edge: n=1: B = (1+1)//2 = 1. black count=1, white count=0. special_black = (0,0) assign 1. There is no white cell. The loop over cells will skip special_black, and for other cells none. So matrix[0][0]=1. Works.
Now confirm for n=3: B=5. black count=5, white=4. special_black assign 5; special_white assign 6. Remaining black cells: 4, assign 1..4; remaining white cells: 3, assign 7,8,9 (B+2=7 to N=9). Good.
Thus algorithm is solid.
Now we must ensure that for n >= 3, special_white (n-1, n-2) is indeed a white cell and not the same as special_black (if n=1? irrelevant). For n=3, (2,1) is white. For n=4, (3,2) white. For n=5, (4,3) white. Good.
But what if n=2? Then special_white = (1,0) which is white but adjacent to (0,0). But we output -1 anyway.
Now we need to implement for t up to 100, n up to 100. Complexity O(n^2) per test, fine.
But double-check: Is there any case where (n-1, n-2) might be a black cell? Parity: (n-1)+(n-2)=2n-3. For n integer, 2n is even, 2n-3 is odd if 3 is odd, so odd -> (i+j) odd -> white. So always white. Good.
Now ensure that special_white is within bounds: For n>=2, n-2 >=0? For n=2, n-2=0, so (1,0) is valid. For n=1, n-2=-1 invalid; we handle n=1 separately.
Now also ensure that special_white is not the same as special_black? For n=2, they are different; for n=3, (0,0) vs (2,1) different; for n=1, not needed.
So overall implementation straightforward.
Before finalizing, let's test a few more n manually with code mental:
n=4 expected matrix: we can compute quickly as earlier.
But is there any possibility that in our assignment, some black cell (like (0,2) assigned 1) and adjacent white cell (like (0,1) assigned 10) difference 9, fine. All cross differences are at least 2 except maybe if 8 and 9 are not adjacent, which we ensure. So it's valid.
But let's double-check a potential pitfall: In our assignment, we fill numbers in increasing order based on row-major for each color. This could lead to a situation where, for example, black number B-1 = 7 (for n=4) placed at some black cell that is adjacent to white number B+2 = 10? diff=3, fine. So no issue.
Thus solution is correct.
Now we should write answer accordingly.
But wait: The problem statement says "If (r_1, c_1) and (r_2, c_2) are adjacent cells, then the numbers written in them must not be adjacent." Means |a-b| != 1. So our construction ensures that.
Now we might also consider if there is any other hidden condition for n=2? Already established impossible.
But is there any other n where the construction fails due to adjacency of B and B+1? For n>=3, we can place them far apart. But we must also ensure that we don't accidentally place B+1 on a cell that is adjacent to B even though we think it's not. Our chosen positions (0,0) and (n-1, n-2) are definitely not adjacent because Manhattan distance = (n-1)+(n-2) = 2n-3, which for n>=3 is >=3 >1. So safe.
But what about n=3: distance = 2+1=3, safe. n=4: 3+2=5, safe. So all good.
Thus final answer: For each test case, if n==2 output -1; else output matrix as described.
Now we need to produce output for t test cases.
Now, to be thorough, I will consider if there is any edge case where n is even and >2 but our special_white might be black? Already confirmed it's white.
Also need to ensure that we correctly compute B = (n*n + 1)//2, which gives number of black cells. But this matches our definition of black as (i+j)%2==0? Let's verify: For n even, total cells = n^2 even, black count = n^2/2 exactly. (n^2+1)//2 = (even+1)//2 = (odd)//2 floor = (even/2) maybe? Example n=4: n^2=16, (16+1)//2=8, which equals 8 = 16/2. So good. For n odd, n^2=9, (9+1)//2=5, which equals ceil(9/2)=5. So yes.
Now for n=1: (1+1)//2=1, correct.
Thus consistent.
Now implement.
Pseudo-code:
def solve():
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n = int(input())
if n == 2:
print(-1)
continue
# initialize matrix
a = [[0]n for _ in range(n)]
N = nn
B = (N + 1)//2 # number of black cells (since (0,0) black)
# assign special positions
a[0][0] = B # max black
if n > 1:
a[n-1][n-2] = B+1 # min white
# counters
black_next = 1
white_next = B+2 # because B+1 already used
# iterate all cells
for i in range(n):
for j in range(n):
if (i == 0 and j == 0) or (i == n-1 and j == n-2):
continue
if (i + j) % 2 == 0: # black
a[i][j] = black_next
black_next += 1
else: # white
# For n=1, there are no white cells, but loop won't enter else because (0,0) skipped and no other cells.
a[i][j] = white_next
white_next += 1
# output
for row in a:
print(' '.join(map(str, row)))
But careful: For n=1, the loop iterates only (0,0) which is skipped, but then we have no assignments for other cells. That's fine because matrix already set a[0][0]=B=1. So output correct.
Now test for n=3 we already did.
Test for n=4 quickly with code mental? Possibly but we trust.
Now verify that white_next may exceed N for the last cell? For n even: black_next starts 1, ends at B-1, exactly B-1 assignments. white_next starts B+2, ends at B+2 + (B-2) = 2B? Actually number of white assignments = remaining white cells = B-1. So white_next final value = (B+2) + (B-2) = 2B? Let's compute: start = B+2, after k increments, value = B+2 + k - 1? Actually we assign first as B+2, then next B+3,... So after assigning to all B-1 white cells, the last value = (B+2) + (B-2) = 2B. Since N=2B, that's fine. So white_next will become 2B+1 after last increment? Actually we increment after each assignment. So after the last assignment, we increment white_next, but we don't use it further. So it's okay.
For n odd: white_next starts B+2, number of white assignments = B-2, last value = (B+2)+(B-3)=2B-1 = N. Good.
So no out-of-range.
Now, is there any risk that for n=2 we incorrectly treat? We already output -1.
But what about n=0? Not in constraints.
Now, think about potential alternative: Could there be any case where n=2 but maybe some other construction exists? We argued it's impossible due to adjacency constraints. Let's confirm via exhaustive reasoning: The grid has 4 cells, each with degree 2 or 3? Actually each corner has degree 2, but each cell is adjacent to two others. As we argued, the only way to avoid adjacency would require placing 1 and 2 in opposite corners, then 3 and 4 in the other two corners, but then 3 adjacent to 2, impossible. Could there be a different arrangement not using opposite corners? Let's try all possibilities manually to be thorough.
We need to assign numbers 1-4. Let's denote positions: A(1,1), B(1,2), C(2,1), D(2,2). Edges: A-B, A-C, B-D, C-D.
Constraint: No edge with diff=1.
We can try brute force mentally. Try place 1 somewhere. Without loss, put 1 at A. Then neighbors B and C cannot be 2. So 2 must be at D (the only non-neighbor of A). So forced: 1 at A, 2 at D. Then remaining numbers 3 and 4 go to B and C. Now check edges: B adjacent to A (1) and D (2). With 3 at B, edges: B-A: |3-1|=2 OK; B-D: |3-2|=1 BAD. If 3 at C, similarly C-D: |3-2|=1 BAD. So impossible. If we start with 1 at B, by symmetry, similar. So indeed impossible. So -1 correct.
Thus solution stands.
Now check n=3 sample output provided: They gave a matrix, but ours is different. That's fine, any valid matrix accepted.
Now ensure output formatting: For each test case, output matrix or -1. Print each row with spaces.
Now consider potential pitfalls: When n is large (100), our loops are fine.
Now verify with n=2: output -1, no matrix.
Now what about n=100? Our construction will produce numbers up to 10000. The difference between B and B+1 is 1, but placed far apart. So valid.
Now we should also check if there is any scenario where our assignment might inadvertently create adjacency between B and B+1 due to wrap-around? Not.
Thus solution is done.
But before finalizing, we should consider if the definition of adjacency in the matrix is only up/down/left/right (common side). Yes. So our construction works.
Now ensure that we used 0-indexing correctly for parity.
If we define black as (i+j)%2==0, then top-left (0,0) is black, top-right (0,n-1): parity = (0 + n-1) = n-1. For n even, n-1 odd => white? Actually for n=4, (0,3) sum=3 odd -> white. That matches standard chessboard.
Thus B is number of black cells.
Now verify for n=4, black cells count = 8, our computed B=8. Good.
Now check assignment: (0,0) is black; (n-1, n-2) for n=4 is (3,2): 3+2=5 odd -> white. Good.
Now what about n=5, (4,3) sum=7 odd -> white. Good.
Now check that we are not accidentally using the same cell for special_white when n=2? But we output -1.
Now final code.
But there is one nuance: For n=1, special_white (0,-1) invalid. We avoid setting it because n>1 condition.
Now, test n=1: B=1, a[0][0]=1. The loop for i in range(1) j in range(1) sees (0,0) skipped. So matrix remains [ [1] ]. Outputs 1. Good.
Now test n=3: We already did, output matrix rows: "5 7 1", "8 2 9", "3 6 4"? Actually our order produced row0: 5 7 1; row1: 8 2 9; row2: 3 6 4. That's valid. But sample output for n=3 is different: "2 9 7", "4 6 3", "1 8 5". Both are valid. So ok.
Now we must ensure that we don't output extra spaces or lines. Print each row as space-separated integers.
Now we are done.
However, before final answer, let's think about the possibility that the problem might require a matrix for all n except 2, but maybe there is another n where it's impossible due to some parity constraints? For instance, n=0? Not.
But we should double-check n=2 is the only one. Could n=1? Works.
Let's attempt n=0? Not.
Thus final solution.
But wait, there is a subtlety: Our construction places numbers in black cells from 1..B (with B the largest) and white cells from B+1..N. However, we must ensure that black cell positions are indeed independent (no adjacency among them). That's true. And white cells similarly. The only potential violation is cross edges. We ensured only one cross pair has diff 1, and they are not adjacent. However, is it possible that another cross pair accidentally has diff 1? Only if the sets are not contiguous intervals? But we assign them as intervals. However, we need to make sure that after we skip the special numbers, we still assign intervals, but the sets become: black numbers = {1,2,...,B-1} ∪ {B} (with B at special), white numbers = {B+1} ∪ {B+2,...,N}. The union still forms the full set with a gap? Actually there is no gap; it's continuous: 1,2,...,B-1,B,B+1,B+2,...,N. So the cross pairs are any black number b in {1,...,B} and any white number w in {B+1,...,N}. The only consecutive numbers between these sets are (B, B+1). Because for any b < B, b+1 ≤ B, so b+1 is not white. For any w > B+1, w-1 ≥ B+1, so w-1 is not black (except possibly w-1 = B+1? That is white). So indeed the only cross consecutive pair is (B, B+1). So safe.
Thus construction stands.
Now confirm that for n even, B = N/2, so B and B+1 are consecutive. For n odd, B = (N+1)/2, B+1 is also consecutive. So yes.
Now implement in code.
Edge Cases:
- n=2 -> output -1.
- n=1 -> output 1.
- n=100 -> works.
Now we must also consider that the problem may have multiple test cases, we need to output each answer.
Now final code.
Potential alternative: We could also produce a matrix by filling the board with numbers in a "snake" pattern that avoids adjacency? But this is simpler.
Now I'll write the final answer.
But before finishing, I should double-check the adjacency condition: "If (r_1, c_1) and (r_2, c_2) are adjacent cells, then the numbers written in them must not be adjacent." So if numbers are 1 and 2, they are adjacent numbers, so they cannot be placed in adjacent cells. That's what we enforced.
Now, is there any scenario where numbers 1 and 2 are placed in same color? They would be not adjacent in grid because same color cells are never adjacent? Actually, same color cells are never adjacent (since grid bipartite). So it's safe to put consecutive numbers on same color cells. In our construction, many consecutive numbers are on same color (e.g., 1 and 2 are both black, 3 and 4 black, etc). That's fine because they are not adjacent cells. So good.
Now, check: In our construction for n=4, black numbers include 1,2,3,4,5,6,7,8. Among these, 7 and 8 are consecutive and both black, but they are not adjacent cells because black cells are not neighbors. However, is it possible that two black cells are adjacent? In a bipartite grid, black cells are never adjacent (they are independent set). So indeed they are not adjacent. So condition satisfied.
Thus all good.
Now I think we have solved.
Now produce final answer.
But wait: Did we correctly compute black count? Using (n*n+1)//2 yields number of cells with (i+j) even if we start with (0,0) even. Let's verify for n=3: cells with even sum: (0,0), (0,2), (1,1), (2,0), (2,2) -> 5 cells, matches B=5. Good.
Now for n=4: even sum cells: (0,0),(0,2),(1,1),(1,3),(2,0),(2,2),(3,1),(3,3) -> 8, matches B=8.
Now for n=5: even sum cells: count? B=13, and we can count quickly: total 25, black should be 13. Yes.
So correct.
Now implementation details: In Python, we can generate matrix as list of lists.
Now note: For n=2, we output -1. There's no trailing spaces.
Now I'll produce final solution in answer.
But before final, consider if there is any issue with n=2 and our construction theoretically would assign (0,0)=B=2, (1,0)=B+1=3 (since n-2=0) but that's adjacent, and the rest assign 1 to remaining black? But we are not outputting that because we check n==2 and output -1. So fine.
Now also check n=2, but what if we swapped roles (assign black numbers to white cells etc)? The problem is symmetric, but since every black and white pair are adjacent, any split that puts B and B+1 on opposite colors forces them adjacent. Could we avoid by not using interval split? Perhaps another construction could work for n=2? Let's attempt all 24 permutations to see if any works. We already did reasoning: the only possible non-adjacent placements for 1 and 2 are opposite corners; then 3 and 4 forced into the other corners, causing adjacency with 2. So impossible. So -1 correct.
Thus final answer.
Now produce final solution.
We'll include explanation in the answer.
Now I'll write the final message. ```python
import sys
def solve() -> None:
it = iter(sys.stdin.read().strip().split())
t = int(next(it))
out_lines = []
for _ in range(t):
n = int(next(it))
if n == 2:
out_lines.append("-1")
continue
# matrix initialized with zeros
a = [[0] * n for _ in range(n)]
N = n * n
black_cnt = (N + 1) // 2 # number of cells with (i+j) even
# special numbers
max_black = black_cnt # goes to a black cell
min_white = black_cnt + 1 # goes to a white cell
# place the critical pair far apart
a[0][0] = max_black # (0,0) is black
if n > 1:
a[n-1][n-2] = min_white # (n-1, n-2) is white and not adjacent to (0,0)
# counters for the remaining numbers
black_next = 1 # 1 .. max_black-1
white_next = min_white + 1 # min_white+1 .. N
for i in range(n):
for j in range(n):
if (i == 0 and j == 0) or (i == n-1 and j == n-2):
continue
if (i + j) % 2 == 0: # black cell
a[i][j] = black_next
black_next += 1
else: # white cell
a[i][j] = white_next
white_next += 1
# append the matrix rows to output
for row in a:
out_lines.append(" ".join(map(str, row)))
sys.stdout.write("\n".join(out_lines))
if name == "main":
solve()