根据题意,B(i,j)若为0,那么它是周围(包括自己)中的最大值,A(i,j)附一个最大值(比如说9)
与B(i,j)相邻的四个格子,如果B(i+p,j+q)(p,q=-1,1)也为0,那么A(i+p,j+q)与A(i,j)相等;
如果B(i+p,j+q)大于0,那么B(i+p,j+q)--(相当于减少一个大于A(i+p,j+q)的A(i,j));
与B(i,j)相邻的四个格子,如果B(i+p,j+q)(p,q=-1,1)也为0,那么A(i+p,j+q)与A(i,j)相等;
如果B(i+p,j+q)大于0,那么B(i+p,j+q)--(相当于减少一个大于A(i+p,j+q)的A(i,j));
判断无解的情况,把做出来的A和B对照,不合理即为NO SOLUTION,合理就输出。
代码如下:
#include <cstdio>
using namespace std;
const int MAXN = 5;
int N, B[MAXN][MAXN] = {0}, tB[MAXN][MAXN] = {0}, A[MAXN][MAXN] = {0};
bool hash[MAXN][MAXN] = {false};
bool find_zero(int &x, int &y)
{
for(int i = 1; i <= N; ++i)
for(int j = 1; j <= N; ++j)
if(!B[i][j] && !hash[i][j]) { x = i, y = j;return true; }
return false;
}
int dfs(int x, int y, int num)
{
int re = 1;
A[x][y] = num;
hash[x][y] = true;
if(x > 1)
{
if(B[x-1][y]) B[x-1][y]--;
else if(!hash[x-1][y]) re += dfs(x-1, y, num);
}
if(y > 1)
{
if(B[x][y-1]) B[x][y-1]--;
else if(!hash[x][y-1]) re += dfs(x, y-1, num);
}
if(x < N)
{
if(B[x+1][y]) B[x+1][y]--;
else if(!hash[x+1][y]) re += dfs(x+1, y, num);
}
if(y < N)
{
if(B[x][y+1]) B[x][y+1]--;
else if(!hash[x][y+1]) re += dfs(x, y+1, num);
}
return re;
}
int main()
{
scanf("%d", &N);
for(int i = 1; i <= N; ++i)
for(int j = 1; j <= N; ++j)
{
scanf("%d", &B[i][j]);
tB[i][j] = B[i][j];
}
for(int i = 0; i <= N + 1; ++i)
for(int j = 0; j <= N + 1; ++j)
A[i][j] = -1;
int rest = N * N, army = 9;
int x, y;
while(rest)
{
if(!find_zero(x, y)) break;
rest -= dfs(x, y, army);
army--;
}
for(int i = 1; i <= N; ++i)
for(int j = 1; j <= N; ++j)
{
int sum = 0;
if(A[i][j] < A[i-1][j]) sum++;
if(A[i][j] < A[i][j-1]) sum++;
if(A[i][j] < A[i+1][j]) sum++;
if(A[i][j] < A[i][j+1]) sum++;
if(sum != tB[i][j])
{
printf("NO SOLUTION\n");
return 0;
}
}
for(int i = 1; i <= N; ++i)
{
printf("%d", A[i][1]);
for(int j = 2; j <= N; ++j)
printf(" %d", A[i][j]);
if(i < N) printf("\n");
}
return 0;
}