SGU 125. Shtirlits(dfs)

来源:互联网 发布:水晶报表软件下载 编辑:程序博客网 时间:2024/06/05 07:36

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

31 2 11 2 11 1 0

Sample Output

1 2 31 4 51 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 longusing 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;}



原创粉丝点击