1 条题解
-
0
文字教学
这道题用DFS+回溯解决,核心是模拟跳棋规则并探索所有可能的跳跃路径:
- 跳棋规则:从当前0格向上下左右4个方向跳,需连续越过至少1个1格,落到下一个未访问的0格;跳过的距离=越过的1的个数+1。
- DFS参数:当前位置
(x,y)和当前已跳的总距离dis。 - 回溯过程:对每个方向探索可行跳跃,标记目标0格为已访问,递归后取消标记(回溯),继续探索其他路径。
- 更新最大值:每次进入DFS时用当前总距离更新最大距离
ans。
代码
#include <bits/stdc++.h> using namespace std; const int N = 105; int g[N][N], vis[N][N]; int n, ans; int dx[4] = {-1, 1, 0, 0}; int dy[4] = {0, 0, -1, 1}; void dfs(int x, int y, int dis) { if (dis > ans) ans = dis; for (int d = 0; d < 4; ++d) { int nx = x + dx[d], ny = y + dy[d]; int cnt = 0; while (nx >= 1 && nx <= n && ny >= 1 && ny <= n) { if (g[nx][ny] == 1) { cnt++; nx += dx[d]; ny += dy[d]; } else if (g[nx][ny] == 0) { if (cnt >= 1 && !vis[nx][ny]) { vis[nx][ny] = 1; dfs(nx, ny, dis + cnt + 1); vis[nx][ny] = 0; } break; } } } } int main() { int x, y; cin >> n >> x >> y; for (int i = 1; i <= n; ++i) for (int j = 1; j <= n; ++j) cin >> g[i][j]; vis[x][y] = 1; ans = 0; dfs(x, y, 0); cout << ans << endl; return 0; }
- 1
信息
- ID
- 2764
- 时间
- 1000ms
- 内存
- 128MiB
- 难度
- 5
- 标签
- 递交数
- 1
- 已通过
- 1
- 上传者
京公网安备 11011102002149号