原文地址:Construct a unique matrix n x n for an input n
已知一个奇数n,根据下面的条件得到一个n×n大小的矩阵:
- 每个元素是1到n之间的一个整数(包含1和n);
- 在同一行,同一列没有相同的数字;
- 所有的1必须距矩阵的中心任意可能的距离,对于一个奇数n,n×n的矩阵中心是cell ((n-1)/2, (n-1)/2)。
输出:
Input : n = 1
Output : 1
Input : n = 3
Output: 3 2 1
1 3 2
2 1 3
Input : n = 5
Output : 5 3 2 4 1
1 4 3 5 2
2 5 4 1 3
3 1 5 2 4
4 2 1 3 5
首先要定下来1的位置。当n=5的时候,这里有一种1的可能位置:
_ _ _ _ 1
1 _ _ _ _
_ _ _ 1 _
_ 1 _ _ _
_ _ 1 _ _
一旦我们定下了1的位置,填补剩下的项就比较简单了。我们逐列填充剩下的数字。对于每个1,我们遍历这个列,在1下面用2, 3,…p来填充,上面用p+1, .. n填充,于是得到下面的矩阵:
5 3 2 4 1
1 4 3 5 2
2 5 4 1 3
3 1 5 2 4
4 2 1 3 5
为了定下1的初始位置,我们遍历所有的行,并跟踪“left”与“right”两列的数字。
- “right”始于n-1,然后在轮过每一行后做递减;
- “left”始于0,然后在轮过每一行后做递增;
以下是上面想法的C++实现
// C++ program to construct an n x n matrix such that
// every row and every column has distinct values.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
int mat[MAX][MAX];
// Fills non-one entries in column j
// Given that there is a "1" at position mat[i][j],
// this function fills other entries of column j.
void fillRemaining(int i, int j, int n)
{
// Initialize value to be filled
int x = 2;
// Fill all values below i as 2, 3, ...p
for (int k=i+1; k<n; k++)
mat[k][j] = x++;
// Fill all values above i as p+1, p+2, .. n
for (int k=0; k<i; k++)
mat[k][j] = x++;
}
// Fills entries in mat[][] with the given set of
// rules
void constructMatrix(int n)
{
// Alternatively fill 1s starting from
// rightmost and leftmost columns. For
// example for n = 3, we get { {_ _ 1},
// {1 _ _} {_ 1 _}}
int right = n-1, left = 0;
for (int i=0; i < n; i++)
{
// If i is even, then fill next column
// from right
if (i%2 == 0)
{
mat[i][right] = 1;
// After filling 1, fill remaining entries
// of column "right"
fillRemaining(i, right, n);
// Move right one column back
right--;
}
else // Fill next column from left
{
mat[i][left] = 1;
// After filling 1, fill remaining entries
// of column "left"
fillRemaining(i, left, n);
// Move left one column forward
left++;
}
}
}
// Driver program to test above function
int main()
{
int n = 5;
// Passing n to constructMatrix function
constructMatrix(n);
// Printing the desired unique matrix
for (int i=0; i<n; i++)
{
for (int j=0 ; j<n; j++)
printf("%d ",mat[i][j]);
printf ("\n");
}
return 0;
}
输出:
5 3 2 4 1
1 4 3 5 2
2 5 4 1 3
3 1 5 2 4
4 2 1 3 5