恳请各位大佬帮忙debug
查看原帖
恳请各位大佬帮忙debug
1313177
the_second_Ryan楼主2024/3/23 21:31

抱歉打扰各位大佬,恳请各位帮忙debug一下 以下为代码,谢谢大家

#include <iostream>
#include <algorithm>
#include <cstring>
#include <stack>
using namespace std;
int h[4] = {0, -1, 0, 1};
int l[4] = {-1, 0, 1, 0};
int a[20][20];//存放地图
int d[20][20];//记录步数
int v[20][20];
int m, n;
int startx, starty, endx, endy;
int prex[20][20];
int prey[20][20];
void dfs(int x, int y, int lucheng) {
    if (x == endx && y == endy) {
        d[x][y] = lucheng;
        stack <int> qx, qy;
        qx.push(endx), qy.push(endy);//倒推前面走过的格子
        while (1) {
            if (qx.top() == startx && qy.top() == starty) {
                break;
            }
            int px = prex[qx.top()][qy.top()];
            int py = prey[qx.top()][qy.top()];
            qx.push(px);
            qy.push(py);
        }
        while (!qx.empty()) {
            if (qx.top() == endx && qy.top() == endy) {
                printf("(%d,%d)", qx.top(), qy.top());
                break;
            }
            printf("(%d,%d)->", qx.top(), qy.top());
            qx.pop();
            qy.pop();
        }//将步数从二维数组中存入栈内,利用先进后出的特性正常输入
        cout << endl;
        return;//第一种路径走完
    }
    d[x][y] = lucheng;
    v[x][y] = 1;
    for (int i = 0; i < 4; i ++) {
        int nx = x + h[i];
        int ny = y + l[i];
        if (nx >= 1 && nx <= n && ny >= 1 && ny <= n && d[nx][ny] == -1 && a[nx][ny]) {
            prex[nx][ny] = x;
            prey[nx][ny] = y;
            dfs(nx, ny, lucheng + 1);
        }
    }
    v[x][y] = 0;
}
int main() {
    cin >> m >> n;
    for (int i = 1; i <= m; i ++) {
        for (int j = 1; j <= n; j ++) {
            cin >> a[i][j];
        }
    }
    cin >> startx >> starty >> endx >> endy;
    memset(d, -1, sizeof(d));
    dfs(startx, starty, 0);
    if (d[endx][endy] == -1) {
        cout << -1;
    }//抵达不了的情况
    return 0;
}
2024/3/23 21:31
加载中...