SGU 125. Shtirlits(dfs)

There is a checkered field of size N x N cells (1 Ј N Ј 3). Each cell designates the territory of a state (i.e. N2 states). Each state has an army. Let A [i, j] be the number of soldiers in the state which is located on i-th line and on j-th column of the checkered field (1£i£N, 1£j£N, 0 £  A[i, j] £  9). For each state the number of neighbors, B [i, j], that have a larger army, is known. The states are neighbors if they have a common border (i.e. £  B[i, j]  £  4). Shtirlits knows matrix B. He has to determine the number of armies for all states (i.e. to find matrix A) using this information for placing forces before the war. If there are more than one solution you may output any of them.

Input

The first line contains a natural number N. Following N lines contain the description of matrix B - N numbers in each line delimited by spaces.

Output

If a solution exists, the output file should contain N lines, which describe matrix A. Each line will contain N numbers delimited by spaces. If there is no solution, the file should contain NO SOLUTION.

Sample Input

3
1 2 1
1 2 1
1 1 0

Sample Output

1 2 3
1 4 5
1 6 7

給你一個數組b,b[i][j]表示座標爲i,j的周圍有b[i][j]個數比你大,讓你找出一個符合條件的a數組。

如果dfs到最後再判斷是否滿足條件,複雜度是9^9,很顯然會超時,所以在搜的過程中就判斷是否可行,不行就剪枝。

#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define LL long long

using namespace std;


int n;
int flag;
int dir[4][2] = {1,0,0,1,-1,0,0,-1};
int a[10][10],b[10][10];


bool judge(int x,int y)
{
    int sum = 0;
    if(x >= 1 && y >= 1 && x <= n && y <= n)
    {
        for(int i=0;i<4;i++)
        {
            int tx = x + dir[i][0];
            int ty = y + dir[i][1];
            if(a[tx][ty] > a[x][y])
                sum++;
        }
        if(sum == b[x][y])
            return true;
        else
            return false;
    }
    return true;
}
void dfs(int x,int y)
{
    if(flag == 1)
        return;
    if(x == n+1)
    {
        if(judge(n,n) == 1)
        {
            flag = 1;
        }
        return ;
    }
    for(int i=1;i<=9;i++)
    {
        a[x][y] = i;
        if(x != 1 && !judge(x-1,y))
            continue;
        if(x == n && !judge(x,y-1))
            continue;
        if(y == n)
            dfs(x+1,1);
        else
            dfs(x,y+1);
        if(flag == 1)
            break;
    }
}
int main(void)
{
    int i,j;
    while(scanf("%d",&n)==1)
    {
        for(i=1;i<=n;i++)
        {
            for(j=1;j<=n;j++)
            {
                scanf("%d",&b[i][j]);
            }
        }
        memset(a,0,sizeof(a));
        flag = 0;
        dfs(1,1);
        if(flag == 1)
        {
            for(i=1;i<=n;i++)
            {
                for(j=1;j<=n;j++)
                    printf("%d ",a[i][j]);
                printf("\n");
            }
        }
        else
            printf("NO SOLUTION\n");
    }

    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章