# 取数游戏
## 题目描述
一个n*m 的由非负整数构成的数字矩阵,你需要在其中取出若干个数字,使得取出的任意两个数字不相邻(若一个数字在另外一个数字相邻 $8$ 个格子中的一个即认为这两个数字相邻),求取出数字和最大是多少。
## 输入格式
第一行有一个正整数T表示了有T组数据。
对于每一组数据,第一行有两个正整数N和M,表示了数字矩阵为 N行 M列。
接下来n行,每行 M个非负整数,描述了这个数字矩阵。
## 输出格式
共 T行,每行一个非负整数,输出所求得的答案。
## 样例 #1
### 样例输入 #1
```
3
4 4
67 75 63 10
29 29 92 14
21 68 71 56
8 67 91 25
2 3
87 70 85
10 3 17
3 3
1 1 1
1 99 1
1 1 1
```
### 样例输出 #1
```
271
172
99
```
## 提示
### 样例解释
对于第一组数据,取数方式如下:
[67] 75 63 10
29 29 [92] 14
[21] 68 71 56
8 67 [91] 25
分析 回溯题
代码
#include<bits/stdc++.h>//万能头文件
using namespace std;
const int d[8][2]={1,0,-1,0,0,1,0,-1,1,1,-1,1,1,-1,-1,-1};//方向数组用来控制搜索时的方向
int t,n,m,s[8][8],mark[8][8],ans,mx;
void dfs(int x,int y){//搜索函数,表示搜索点(x,y)
if(y==m+1){//当y到边界时,搜索下一行
dfs(x+1,1);
return;
}
if(x==n+1){//当x到边界时,搜索结束,刷新最大值
mx=max(ans,mx);
return;
}
dfs(x,y+1);// 不取此数的情况
if(mark[x][y]==0){ //取此数的情况(需保证此数周围没有取其他数,即mark[i][j]==0)
ans+=s[x][y];
for(int fx=0;fx<8;++fx){ //标记周围的数
++mark[x+d[fx][0]][y+d[fx][1]];
}
dfs(x,y+1);
for(int fx=0;fx<8;++fx){ //回溯
--mark[x+d[fx][0]][y+d[fx][1]];
}
ans-=s[x][y];
}
}
int main(){
cin>>t;
while(t--){
memset(s,0,sizeof(s));
memset(mark,0,sizeof(mark));//在做每个数据前都要初始化数组
cin>>n>>m;
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j){
cin>>s[i][j];
}
}
mx=0;
dfs(1,1);//从点(1,1)开始搜索
printf("%d\n",mx);//输出答案
}
return 0;
}