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. 0 <= 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
题目意思:求一个矩阵,给出原矩阵某数周围比他大的数的个数矩阵。
解题思路:从头开始从左往右从上往下枚举每一个元素,到第二行及以下时检查上一行对应元素是否满足条件,枚举到最后一个元素时,检查最后一行所有元素是否满足条件。
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define maxn 5
int num[maxn][maxn];
int ans[maxn][maxn];
int n;
bool ok;
/
bool inside(int x,int y){
return x>=0 && x<n && y>=0 && y<n;
}
bool check(int x, int y){
int cnt = 0;
if(inside(x-1,y) && ans[x-1][y] > ans[x][y]) cnt++; // up
if(inside(x+1,y) && ans[x+1][y] > ans[x][y]) cnt++; // down
if(inside(x,y-1) && ans[x][y-1] > ans[x][y]) cnt++; // left
if(inside(x,y+1) && ans[x][y+1] > ans[x][y]) cnt++; // right
return cnt==num[x][y];
}
bool dfs(int x,int y){
if(ok) return true;
if(x==n && y==0){
for(int i=0;i<n;i++){
if(!check(n-1,i)) return false;
}
return ok = true;
}
int xx,yy;
if(y==n-1) {
xx = x+1;
yy = 0;
}else{
xx = x;
yy = y+1;
}
for(int i=0;i<10;i++){
ans[x][y] = i;
if(x>0) {
if(check(x-1,y)) {
dfs(xx,yy);
if(ok) return true;
}
}
else {
dfs(xx,yy);
if(ok) return true;
}
}
return ok;
}
int main(){
cin >> n;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin >> num[i][j];
}
}
ok = false;
memset(ans,-1,sizeof(ans));
if(!dfs(0,0)){
cout << "NO SOLUTION" <<endl;
}else{
for(int i=0;i<n;i++){
cout << ans[i][0];
for(int j=1;j<n;j++){
cout << " "<<ans[i][j];
}
cout << endl;
}
}
return 0;
}