关于取路径(全局方案数组+逆序输出)
取路径 = 记录方案(方案数组)
点击查看代码
#include <bits/stdc++.h>
using namespace std;
#define N 16
int n, m, g[N][N], a, b, sx, st, v[N][N], ans;
struct AK{
int x, y;
};
AK d[1000];
int dx[] = {0, -1, 0, 1}, dy[] = {-1, 0, 1, 0};
void dfs(int a, int b, int u) {
if(a == sx && b == st) {
for(int i = 0; i < u; ++ i) {
cout << '(' << d[i].x << ',' << d[i].y << ')';
if(i + 1 < u) cout << "->";
}
cout << endl;
ans = 1;
return ;
}
for(int i = 0; i < 4; ++ i) {
int x = a + dx[i], y = b + dy[i];
if(x >= 1 && x <= n && y >= 1 && y <= m && g[x][y] == 1 && v[x][y] == 0) {
v[x][y] = 1;
d[u].x = x, d[u].y = y;
dfs(x, y, u + 1);
v[x][y] = 0;
}
}
}
int main() {
cin >> n >> m;
for(int i = 1; i <= n; ++ i) {
for(int j = 1; j <= m; ++ j) {
cin >> g[i][j];
}
}
cin >> a >> b;
cin >> sx >> st;
d[0].x = a, d[0].y = b;
v[a][b] = 1;
dfs(a, b, 1);
if(!ans) cout << -1 << endl;
return 0;
}
点击查看代码
void print() {
flag = 1;
for(int h = 0; h <= k - 1; ++ h) {
printf("(%d,%d)->", ans[h][0], ans[h][1]);
}
printf("(%d,%d)\n", bx, by);
}
void dfs(int x, int y) {
for(int i = 0; i < 4; ++ i) {
if(a[x + cx[i]][y + cy[i]] == 1 && vis[x + cx[i]][y + cy[i]] == 0) {
vis[x][y] = 1;
ans[k][0] = x, ans[k][1] = y;
++ k;
dfs(x + cx[i], y + cy[i]);
vis[x][y] = 0;
-- k;
}
}
}
浙公网安备 33010602011771号