现此题用 dp 做完了,但不知为什么 dfs 要一行一行逐个算
我每次往周围 12 个方向扩展为什么不对,求教
#include <iostream>
#include <cstring>
using namespace std;
const int S = 10;
const int dir1[17][2] = {{0}, {0, 2}, {0, -2}, {1, 2}, {-1, 2}, {1, -2}, {-1, -2}, {2, 2}, {-2, -2},
{2, 0}, {-2, 0}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}, {-2, 2}, {2, -2}};
const int dir2[9][2] = {{0}, {1, 0}, {0, 1}, {0, -1}, {-1, 0}, {-1, 1}, {1, -1}, {-1, -1}, {1, 1}};
int T, n, m;
int a[S][S], ans;
bool vis[S][S];
bool in(int x, int y) {
return x >= 1 && x <= n && y >= 1 && y <= m;
}
bool far(int x, int y) {
for (int i = 1; i <= 8; i++) {
int nx = x + dir2[i][0],
ny = y + dir2[i][1];
if (in(nx, ny) && vis[nx][ny]) {
return false;
}
}
return true;
}
void dfs(int x, int y, int sum) {
ans = max(ans, sum);
for (int i = 1; i <= 16; i++) {
int nx = x + dir1[i][0],
ny = y + dir1[i][1];
if (in(nx, ny) && far(nx, ny) && !vis[nx][ny]) {
vis[nx][ny] = true;
dfs(nx, ny, sum + a[nx][ny]);
vis[nx][ny] = false;
}
}
for (int i = 1; i <= 8; i++) {
int nx = x + dir2[i][0],
ny = y + dir2[i][1];
if (in(nx, ny) && far(nx, ny) && !vis[nx][ny]) {
vis[nx][ny] = true;
dfs(nx, ny, sum + a[nx][ny]);
vis[nx][ny] = false;
}
}
}
int main() {
cin >> T;
while (T--) {
ans = 0;
memset(vis, false, sizeof(vis));
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
}
}
dfs(0, 0, 0);
cout << ans << endl;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
vis[i][j] = false;
}
}
}
return 0;
}