版权声明:晓程原创 https://blog.csdn.net/qq_43469554/article/details/89205876
题目描述
一个N×M的由非负整数构成的数字矩阵,你需要在其中取出若干个数字,使得取出的任意两个数字不相邻(若一个数字在另外一个数字相邻8个格子中的一个即认为这两个数字相邻),求取出数字和最大是多少。
输入输出格式
输入格式:
第1行有一个正整数T,表示了有T组数据。
对于每一组数据,第一行有两个正整数N和M,表示了数字矩阵为N行M列。
接下来N行,每行M个非负整数,描述了这个数字矩阵。
输出格式:
T行,每行一个非负整数,输出所求得的答案。
原题链接:https://www.luogu.org/problemnew/show/P1123
/*
输入:
1
4 4
67 75 63 10
29 29 92 14
21 68 71 56
8 67 91 25
输出:
271
*/
#include <iostream>
#include <cstring>
using namespace std;
int a[10][10];
int vis[10][10];
int n, m;
int ans;
//判断周围8个方向是否被标记(即已选)
int f(int x, int y)
{
for (int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
if (i == 0 && j == 0)//剔除本身那个点
{
continue;
}
int tx = i + x;
int ty = j + y;
if (tx < 1 || tx > n || ty < 1 || ty > m)
{//越界
continue;
}
if (vis[tx][ty])
{
return 0;
}
}
}
return 1;
}
void dfs(int x, int y, int dis)
{//逐个遍历每个数字,从第一行开始
if (x > n)
{//遍历完毕
ans = max(ans, dis);
return;
}
//继续当前行的下一个数
int tx = x, ty = y + 1;
if (ty > m)//当前行遍历完了,继续下一行第一个数
{
tx++;
ty = 1;
}
//如果当前数字合法(即8个方向没有已选的数),可先尝试选择它
if (f(x, y))
{
vis[x][y] = 1;
dfs(tx, ty, dis + a[x][y]);
vis[x][y] = 0;
}
//也可不选它
dfs(tx, ty, dis);
}
int main()
{
int t;
cin >> t;
while (t--)
{
ans = -0x3f3f3f3f;
memset(vis, 0, sizeof(vis));
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
cin >> a[i][j];
}
}
dfs(1, 0, 0);
cout << ans << endl;
}
return 0;
}